1

我正在用 pygame 在 python 中制作一个蛇游戏,为了移动角色,我有一个整数,它是它应该移动的角度的度数。有什么办法可以让 x 和 y 的变化根据度数移动它?例如:func(90) # [0, 5]func(0) # [5, 0]

4

3 回答 3

9
import math

speed = 5
angle = math.radians(90)    # Remember to convert to radians!
change = [speed * math.cos(angle), speed * math.sin(angle)]
于 2010-12-28T23:20:49.980 回答
5

角度的正弦和余弦乘以移动的总量,将为您提供 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)
于 2010-12-28T23:20:29.823 回答
3

如果蛇只能以特定角度(例如 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 度增量移动)。

于 2010-12-28T23:57:40.847 回答