Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python将度转换为x方向的变化和y方向的变化_Python_Coordinates_Pygame_Degrees - Fatal编程技术网

python将度转换为x方向的变化和y方向的变化

python将度转换为x方向的变化和y方向的变化,python,coordinates,pygame,degrees,Python,Coordinates,Pygame,Degrees,我正在用pygame用python制作一个蛇游戏,为了移动角色,我有一个整数,它应该移动角度的度数。有什么方法可以让x和y的变化基于度来移动它吗?例如:func(90)#[0,5]或func(0)#[5,0]角度的正弦和余弦乘以移动总量,将给出X和Y变化 import math def func(degrees, magnitude): return magnitude * math.cos(math.radians(degrees)), magnitude * math.sin(mat

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

角度的正弦和余弦乘以移动总量,将给出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)

角度的正弦和余弦乘以移动的总量,将得到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度的增量移动)。

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

Byers,我不知道数学。弧度,谢谢你的例子!我把我的改成了match。拜尔斯,我不懂数学。弧度,谢谢你的例子!我把我的改成了匹配的。简短的解释,冗长的例子。简短的解释,冗长的例子。