python – How to make an enemy follow the player in pygame?

You need to reduce the distance between the enemy and the player by changing the enemy’s position. This can be done by finding the difference between their positions and then using that vector to compute a normalized (unit length) direction vector. With that, change the enemy’s position by adding its speed times the direction vector to it.

One way of doing this would be by adding a method like the following to your Enemy class. The mathmatical operations can be done using the built-in math module or the pygame.math module. The latter also has support for a 2D Vector2 class, so it would probably be the better one to actually use.

import math
import pygame
from pygame.locals import *

class Enemy(object):
    ...
    def move_towards_player(self, player):
        # Find direction vector (dx, dy) between enemy and player.
        dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
        dist = math.hypot(dx, dy)
        dx, dy = dx / dist, dy / dist
        # Move along this normalized vector towards the player at current speed.
        self.rect.x += dx * self.speed
        self.rect.y += dy * self.speed

    # Same thing using only pygame utilities
    def move_towards_player2(self, player):
        # Find direction vector (dx, dy) between enemy and player.
        dirvect = pygame.math.Vector2(player.rect.x - self.rect.x,
                                      player.rect.y - self.rect.y)
        dirvect.normalize()
        # Move along this normalized vector towards the player at current speed.
        dirvect.scale_to_length(self.speed)
        self.rect.move_ip(dirvect)

You will need to add checks to determine whether the enemy object will overshoot and thereby hit the player along the way if it moves this distance, and react accordingly. Hint: A collision will occur whenever the amount to be moved—the length of the speed vector—is greater or equal to the distance between them.

Loading...

(Visited 5 times, 1 visits today)