【发布时间】:2015-04-10 01:53:57
【问题描述】:
我正在尝试创建一个游戏,当玩家点击时,玩家会射击 射弹在点击点的同一路径上。到目前为止,我的代码运行良好,除了玩家点击的距离越远,它移动的越快。代码如下:
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
【问题讨论】:
-
当您点击更远的
x2, y2时,会变大(或变小)。这意味着slope_y, slope_x变得更大。这意味着您增加rect.x, rect.y的增量更大。因此,无论何时您更新导弹位置,它都会根据您单击的位置而增加或减少。 -
我明白,我只是想知道是否有任何方法可以防止这种情况发生。不过还是谢谢。
标签: python pygame sprite angle