Moving forward after angle change. Pygame

To move the tank in the direction which is faced, wirte a method, that computes a direction vector, dependent on an velocity argument and the self.angle attribute. The nagle and the velocity define a vector by Polar coordinats.
Add the vector to it’s current position (self.pos). Finally update the self.rect attribute by the position:

class Tank(pygame.sprite.Sprite):
    # [...]

    def move(self, velocity):
        direction = pygame.Vector2(0, velocity).rotate(-self.angle)
        self.pos += direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])

Invoke the method when up or down is pressed:

class Game:
    # [...]

    def handle_events(self):
        # [...]

        if keys[pygame.K_UP]:
            self.tank.move(-5)
        if keys[pygame.K_DOWN]:
            self.tank.move(5)

The movement direction of the bullets can be computed similar:

class Bullet(pygame.sprite.Sprite):

    def __init__(self, tank):
        #[...]

        self.rect = self.image.get_rect()
        self.angle = tank.angle
        self.pos = pygame.Vector2(tank.pos)
        self.rect.center = round(self.pos.x), round(self.pos.y)
        self.direction = pygame.Vector2(0, -10).rotate(-self.angle)

    def update(self):
        self.pos += self.direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])

To make the bullet bounce, you have to reflect the direction when the bullet hits a border:

class Bullet(pygame.sprite.Sprite):
    # [...]

    def update(self):
        self.pos += self.direction
        self.rect.center = round(self.pos.x), round(self.pos.y)

        if self.rect.left < 0:
            self.direction.x *= -1
            self.rect.left = 0
            self.pos.x = self.rect.centerx
        if self.rect.right > 1060:
            self.direction.x *= -1
            self.rect.right = 1060
            self.pos.x = self.rect.centerx 
        if self.rect.top < 0:
            self.direction.y *= -1
            self.rect.top = 0
            self.pos.y = self.rect.centery
        if self.rect.bottom > 798:
            self.direction.y *= -1
            self.rect.right = 798
            self.pos.y = self.rect.centery

Leave a Comment