我正在尝试创建一个游戏,当玩家点击时,玩家会射击 点击相同路径上的抛射物。到目前为止,我的代码工作得很好,除了玩家点击的距离越远,移动的速度就越快。这是代码:
class Projectile(pygame.sprite.Sprite):
x2 = 0
y2 = 0
slope_x = 0
slope_y = 0
attack_location = ()
slope = 0
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.x = 390
self.rect.y = 289
self.attack_location = (mouse_x,mouse_y)
self.mask = pygame.mask.from_surface(self.image)
self.x2 = self.attack_location[0]
self.y2 = self.attack_location[1]
self.slope_y = self.y2 - 300
self.slope_x = self.x2 - 400
def update(self):
self.rect.x += (self.slope_x) / 15
self.rect.y += (self.slope_y) / 15
我的代码有点草率和简单,但我想知道是否有办法将速度设置为常数,或者甚至可以使用三角法来使射弹在一个角度上运动。
实际上,我已经成功地对矢量进行了标准化,但是射弹的出现就好像它来自(0,0),但角色的位置是(400,300)。我想知道是否有任何方法可以使载体开始于(400,300),或者是否有另一种解决方案来解决我原来的问题。谢谢!这是代码:
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
self.attack_location = (mouse_x,mouse_y)
self.mask = pygame.mask.from_surface(self.image)
self.x2 = self.attack_location[0]
self.y2 = self.attack_location[1]
self.d = math.sqrt(((self.x2)**2) + ((self.y2)**2))
self.slope_x = self.x2 / self.d
self.slope_y = self.y2 / self.d
def update(self):
self.rect.x += (self.slope_x) * 10
self.rect.y += (self.slope_y) * 10
答案 0 :(得分:1)
您必须规范化方向向量。 像这样:
d = math.sqrt(mouse_x * mouse_x + mouse_y * mouse_y)
self.slope_x = mouse_x / d - 300
self.slope_y = mouse_y / d - 400