# An algorithm to make one object follow another on a 2D grid

I am using Greenfoot, but this can apply to pretty much any 2D engine.

So my question is a basic one that I somehow couldn't find an answer to already. Basically, if I have an enemy and the player, how can I make the enemy follow them? The player can move in all 4 directions, and the enemy can move in any direction, whichever one is faster. It would be done using a method that accepts an integer for speed, and an in-game object to move towards (an Actor in Greenfoot). It shouldn't simply teleport there but move closer by however much the value for speed is. And this would have to be done without rotating the image of the enemy.

This is in Java but if the answer you provide is in pseudo-code or a similar language (such as c++ or c#) I can still use it.

• Path finding is an algorithm to make one object follow another on a 2D grid, isn't it? Why not applying path finding to the enemy and the player's position and letting the enemy following the updated path each time? Commented May 11, 2019 at 13:59
• @Trilarion I'm...unsure. I don't know how to do that either... Commented May 11, 2019 at 17:16

Here is a pretty simple and general method that I think satisfies the conditions.

Let's call the player position (x_p, y_p) and the enemy position (x_e, y_e).

Next, we'll calculate the direction that would move the enemy onto the player. This is (x_e - x_p, y_e - y_p). We can call this (x_d, y_d) where the d is for distance.

The next thing we want to do is to normalise the distance. This will make the length of the distance vector exactly equal to 1. This will also give non-integer values which may or may not be suitable for your grid.

You want to use the Pythagoras theorem to find the length of the vector, and divide by the length. So let's call the normal vector (x_n, y_n) which is (x_d / D, y_d / D) where D = sqrt(x_d * x_d + y_d * y_d).

Now what we have is a direction from the enemy to the player, and the length of this direction is exactly 1 unit whichever way it is pointing. We can easily adjust a speed factor here by updating the enemy with (x_n * speed, y_n * speed). This will move the enemy in exactly speed units toward the player.

• Also, I should note to anyone else reading this in the future with the same problem: It only works because in Greenfoot even though coordinates are stored as ints you can store them as doubles instead, so the algorithm works. That being said I tried to use it as just ints and it compiles but doesn't work as intended, so if you're using an engine that can only use ints you'll need to find something else. Commented May 12, 2019 at 14:12