I set variables for the distance between the enemy and the player along the x-axis and y-axis. My plan is to move the enemy along the hypotenuse formed by y and x-axis line at a constant speed. The thing is I'm not sure how to set x and y speed of the enemy so that it will adjust dynamically to the changing position of the player and still maintain a constant speed. I thought that maybe I could find the angle at which enemy approaches the player and do something with that, but I couldn't think of anything.


1 Answer 1


You should take a look at some vector math stuff, here's an example of a Vector class that will help you quite a bit in implementing this sort of logic. I think this is without bugs, but who knows.

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    def __div__(self, scalar):
        return Vector(self.x / scalar, self.y / scalar)

    def length(self):
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5

    def normal(self):
        return self / self.length()

You can use it in place of every position, distance, velocity and so on.

player.position = Vector(5, 5)
enemy.position = Vector(7, 8)

It makes logic like you're case very simple! Just subtract the enemy's position from the player's to get the direction the enemy should move towards the player. Make sure you normalize that (create a vector with length 1) and then you can multiple it by some speed value and add it back to the enemy's position to have him move.

enemy_speed = 0.1

for _ in range(10):
    enemy_position += (player_position - enemy_position).normal() * enemy_speed 
    print enemy_position

As a quick side note, you pretty much never need to use angles. Vectors are great at specifying directions, whereas angles are used (but not even that great at) specifying rotations. A rotation being like a transformation, taking an object in some orientation and then applying a rotation to it. That is pretty much the only place where angles ought to be used, vectors are super handy otherwise.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .