我正在用Pygame在Python中制作蛇游戏,并且为了移动角色,我有一个整数,这是它应该移动的角度的程度。有什么办法可以根据学位获得X和Y的更改?例如: func(90) # [0, 5] 或者 func(0) # [5, 0]

有帮助吗?

解决方案

import math

speed = 5
angle = math.radians(90)    # Remember to convert to radians!
change = [speed * math.cos(angle), speed * math.sin(angle)]

其他提示

角度的正弦和余弦乘以移动的总量,将为您带来X和Y的变化。

import math
def func(degrees, magnitude):
    return magnitude * math.cos(math.radians(degrees)), magnitude * math.sin(math.radians(degrees))

>>> func(90,5)
(3.0616169978683831e-16, 5.0)
>>> func(0,5)
(5.0, 0.0)

如果蛇只能以某些角度(例如90度或45度)移动,这是这种游戏中典型的,那么您只能使用4或8个方向。您可以将角度除以允许的增量并获取方向索引,然后将其用来将其索引到X/Y偏移量的表中。这将比使用三角学快得多。

x, y = 100, 100   # starting position of the snake

direction = angle / 90 % 4   # convert angle to direction

directions = [(0,-1), (1, 0), (0, 1), (-1, 0)]   # up, right, down, left

# convert the direction to x and y offsets for the next move
xoffset, yoffset = directions[direction]

# calculate the next move
x, y = x + xoffset, y + yoffset

更好的是,完全使用角度概念,只使用方向变量。然后,旋转蛇是逐步增加或减小方向的简单问题。

# rotate counter-clockwise
direction = (direction - 1) % 4

# rotate clockwise
direction = (direction + 1) % 4

如果需要,可以轻松地将其扩展到8个方向(以45度增量移动)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top