我正在创建一个基础的坦克游戏,目前正在开发坦克的炮管部分。我已经成功让炮管围绕一个轴旋转,并且通过按下“a”和“d”键使其移动,但有时候当炮管旋转后再移动时,它会出现向右移动的情况。这是代码:
class tankGun(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = tankGunImage
self.rect = self.image.get_rect()
self.x = 400
self.xx = 410
self.y = 400
self.rect.x = self.x
self.rect.y = self.y
self.angle = 0
self.original = self.image
tankGunList.add(self)
tankGunList.draw(gameDisplay)
def rotate(self, chk):
test = False
if chk == 1:
self.angle += 1
elif chk == 2:
self.angle -= 1
if self.angle > 0 and self.angle < 180:
test = True
else:
if chk == 1:
self.angle = 180
elif chk == 2:
self.angle = 0
if test == True:
self.image = pygame.transform.rotate(self.original, self.angle)
tankGunList.clear(gameDisplay, background)
tankGunList.draw(gameDisplay)
self.rect = self.image.get_rect(center = self.rect.center)
def move(self, chk):
self.x += chk
self.xx = self.x + 10
self.rect.x = self.x
tankGunList.clear(gameDisplay, background)
tankGunList.draw(gameDisplay)
(注:chk作为移动的+1或-1,旋转的1或2发送。这只是检测按下哪个键的一种方法。)
self.x
的值始终与self.rect.x
相同,因此您只需使用self.rect.x
并删除self.x
-self.y
也是如此。 - furastankGunList.draw(gameDisplay)
。你应该只在主循环中绘制一次。 - furas