I am creating a basic tanks game and I am currently working on the gun of the tank. I have managed to make the gun rotate around an axis and it moves whenever you press the "a" and "d" keys but sometimes when the gun has been rotated and then is moved, it moves to the right for some reason. Here is the code:
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)
(Side note: chk is sent in as either +1 or -1 for the movement and 1 or 2 for the rotation. It's just a way of detecting which key was pressed.)