简体   繁体   English

Python / Pygame中的角运动

[英]Angular Movement in Python/Pygame

Me and a few friends are messing around with a new shooting mechanic. 我和几个朋友正在找一个新的射击技师。 The idea is if you click left mouse button, your character rotates left, if you click right, the player rotates right, and if you click both, the player goes backwards. 这个想法是,如果您单击鼠标左键,则角色向左旋转,如果您单击右键,则播放器向右旋转,如果同时单击两者,则播放器将向后移动。 Here is our code: 这是我们的代码:

if char_image_number == (0, 0, 0):
        char_image = pygame.image.load(player_none).convert_alpha()
        char_image = pygame.transform.rotate(char_image, angle)

        screen.blit(char_image,(540, 260))
        pygame.display.update()

elif char_image_number == (1, 0, 0):
        print (angle)
        char_image = pygame.image.load(player_left).convert_alpha()
        angle+=1
        char_image = pygame.transform.rotate(char_image, angle)
        bullets.append(
        screen.blit(char_image,(540, 260))
        pygame.display.update()

elif char_image_number == (0, 0, 1):
        print (angle)
        angle-=1
        char_image = pygame.image.load(player_right).convert_alpha()
        char_image=pygame.transform.rotate(char_image, angle)

        screen.blit(char_image,(540, 260))

        pygame.display.update()
elif char_image_number == (1, 0, 1):
        char_image = pygame.image.load(player_both).convert_alpha()
        char_image = pygame.transform.rotate(char_image, angle)

        screen.blit(char_image,(540, 260))
        pygame.display.update()

How would we be able to make it go backwards, from the current angle it is facing? 从当前的角度来看,我们如何才能使其退回?

This is a math problem. 这是一个数学问题。 Any offset to push the image backwards is going to be a composite offset of x and y. 向后推动图像的任何偏移将是x和y的复合偏移。 This takes trigonometry to figure out. 这需要三角学来解决。

In trig, sin(angle) = delta_y / distance_moved in your case. 在trig中, sin(angle) = delta_y / distance_moved在您的情况下。

and

cos(angle) = delta_x / distance_moved

What you need to do is take distance_moved , how many pixels you want the image to travel every frame, and multiply that by the sin or cos of the angle. 您需要做的是distance_moved ,您希望图像每帧移动多少像素,然后将其乘以角度的sincos That will figure out the change in y and x you need to offset the sprite by. 这样可以找出y和x的变化,您需要使用这些偏移来抵消精灵。

In Python and many other languages, you will need the angle in radians (pretty standard unit). 在Python和许多其他语言中,您将需要以弧度(漂亮的标准单位)为单位的角度。 This mathematical unit represents 180 degrees in one Pi . 这个数学单位表示一个Pi中的180度。 To convert degrees to radians, you divide by 180 and multiply by Pi. 要将度数转换为弧度,请除以180,然后乘以Pi。

In Python: 在Python中:

import math

def convert_degrees(degrees):
    return degrees / 180.0 * math.pi

Examples of sin and cos: 罪恶和cos的例子:

import math
example = 2.0 * math.sin(math.pi) 
example2 = 3.0 * math.cos(convert_degrees(120))

I'll leave the rest to you to figure out. 我会把剩下的交给你解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM