我在移动精灵时遇到问题。我可以毫无问题地在 x 轴和 y 轴上移动它们。我不知道如何才能按照某个角度移动它们。我的意思是,我正在尝试创建一个函数,其中包括我尝试移动的对象、其速度和方向(应以度为单位测量)。就像是:
MovingObject(obj,speed,direction) #this is the function I'm trying to define
它更像是一个“生成函数”而不仅仅是运动......举个例子,我想创建一个“Bullet”类的对象,并希望它遵循一定的方向(当然与x和y轴不同) )
实际上我不清楚如何做这样的事情,我想要一些建议才能实现这一目标。
感谢您阅读本文!
编辑:
@Joran Beasley,我尝试按照你告诉我的去做......但我想我做错了......
import pygame, math, time
screen=pygame.display.set_mode((320,240))
clock=pygame.time.Clock()
pygame.init()
def calculate_new_xy(old_xy,speed,angle_in_radians):
new_x = old_xy.x + (speed*math.cos(angle_in_radians))
new_y = old_xy.y + (speed*math.sin(angle_in_radians))
return new_x, new_y
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y,direction,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((16, 16))
self.image.fill((255,0,0))
self.rect=self.image.get_rect()
self.rect.center=(x,y)
self.direction=math.radians(direction)
self.speed=speed
def update(self):
self.rect.center=calculate_new_xy(self.rect,self.speed,self.direction)
spr=pygame.sprite.Group()
bullet=Bullet(160,120,45,1); spr.add(bullet)
play=True
while play:
clock.tick(60)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
play=False
screen.fill((0,0,0))
spr.update()
spr.draw(screen)
pygame.display.flip()
pygame.quit()
物体移动,但……不朝指定方向移动……