我正在为自己做一个实用程序,可以轻松地将学位转换为X和Y在游戏中的启用,而我陷入了问题;试图在屏幕上以程度移动玩家。我发现多个不起作用的公式,我需要一些帮助。这是我发现的代码:
def move(degrees, offset):
x = math.cos(degrees * 57.2957795) * offset # 57.2957795 Was supposed to be the
y = math.sin(degrees * 57.2957795) * offset # magic number but it won't work.
return [x, y]
我运行此操作:
move(0, 300)
输出:
[300.0, 0.0]
效果很好,但是当我这样做时:
move(90, 300)
它输出了此:
[-89.8549554331319, -286.22733444608303]
您的方法几乎是正确的。您应该将弧度用于罪恶/cos功能。这是我通常在C 中使用的方法(移植到Python )进行2D运动。
import math
def move(degrees, offset)
rads = math.radians(degrees)
x = math.cos(rads) * offset
y = math.sin(rads) * offset
return x, y
数字正确,但操作是错误的。为了将学位转换为弧度,您需要将每半圆划分180度,然后每半圆乘以Pi Readians。这相当于划分与您拥有的常数。
您可以使用pygame.math.Vector2
类的from_polar
方法来设置向量的极性坐标。然后,您可以使用此矢量来调整精灵或矩形的位置。
import pygame as pg
from pygame.math import Vector2
def move(offset, degrees):
vec = Vector2() # Create a zero vector.
vec.from_polar((offset, degrees)) # Set its polar coordinates.
return vec
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')
rect = pg.Rect(300, 200, 30, 20)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
# Use the vector that `move` returns to move the rect.
rect.move_ip(move(50, 90))
screen.fill(BG_COLOR)
pg.draw.rect(screen, BLUE, rect)
pg.display.flip()
clock.tick(30)
pg.quit()