0

So far, the enemies in my game only fire straight down. I want to be able to aim at the player. This is my Enemy class's shoot method.

class Enemy(sprite.Sprite):

    def shoot(self):
        # Origin position, direction, speed
        # Direction of (0,1) means straight down. 0 pixels along the x axis, and +1 pixel along the y axis
        # Speed of (10,10) means that every frame, the object will move 10 px along the x and y axis.
        self.bullets.shoot(self.rect.center, (0,1), (10,10))

self.bullets is an instance of my BulletPool class.

class BulletPool(sprite.Group):

    def shoot(self, pos, direction, speed):

        # Selects a bullet from the pool
        default = self.add_bullet() if self.unlimited else None
        bullet = next(self.get_inactive_bullets().__iter__(), default)
        if bullet is None:
            return False

      
        # Sets up bullet movement
        bullet.rect.center = pos
        bullet.start_moving(direction)
        bullet.set_speed(speed)
        
        # Adds bullet to a Group of active bullets
        self.active_bullets.add(bullet)

And here is my Bullet class.

class Bullet(sprite.Sprite):

    def update(self):
        self.move()

    def set_speed(self, speed):
        self.speed = Vector2(speed)

    def start_moving(self, direction):
        self.direction = Vector2(direction)
        self.is_moving = True

    def stop_moving(self):
        self.is_moving = False

    def move(self):
        if self.is_moving:
            x_pos = int(self.direction.x*self.speed.x)
            y_pos = int(self.direction.y*self.speed.y)

            self.rect = self.rect.move(x_pos,y_pos)

Using this, I can only make sprites go straight up (0,-1), down (0,1), left (-1,0) or right (1,0), as well as combining combining x and axes to make a 45 degree angle, (i.e. (1,1) is going down and right). I don't know how to angle something to make it go towards a particular direction other than these. Should I change the way I move my objects? I use the same methods to move my player, and it works perfectly when it's just taking controls from the arrow keys.

Eigel Asinas
  • 91
  • 2
  • 6
  • Please provide the expected [MRE](https://stackoverflow.com/help/minimal-reproducible-example). Show where the intermediate results deviate from the ones you expect. We should be able to paste a single block of your code into file, run it, and reproduce your problem. This also lets us test any suggestions in your context. – Prune Jan 08 '21 at 05:58
  • You could use the player's rect center to get his current coordinate and fire at him. – Savannah Madison Jan 08 '21 at 06:15

0 Answers0