Unity - Calculating the direction to another GameObject

Player. Where are you? I need some fresh flesh…

Timo Schmid
Nerd For Tech
4 min readJun 14, 2021

--

Okay, no worries. We have a screen between us, so nothing will happen to you ;-)

Anyways. You might have played some games before in which enemies are chasing you. Take Minecraft as an example. Remember the zombies chasing you at night? Or, to turn the paper around, games allowing you to use a magnet to get coins in an easy way. How does that work?

Let’s get started by a little theory first.

A chasing enemy always knows your location and the shortest way to reach you, the distance to you.

Remember the following formula? a² + b² = c²
That’s exactly what’s used here as well!

We have the direction length of the x and y-axis, a and b. Now we just need to calculate c to get the distance vector!

5² = 25
3² = 9
c² = a² + b²
c² = 25 + 9 = 34
c = √34 →
5,83

The distance is 5.83 units!

Coding this behavior
We went through the theoretical part of the article. But how is the code working? How to implement such a mathematical algorithm?
It’s easier than you think. Trust me. Trust a guy who sucks at Maths at school.

Let’s take a look at how to calculate the direction:

To make this vector visible, Unity has a function called Debug.DrawRay(). This will create a little line to visualize the calculated vector.

Entering that method into the IDE, we will get the following tooltip:

We need at least 2 arguments:

  • The start position of the line
  • The end position (or the direction) of the line

Additionally, we can manipulate the color of the line and set a time for how long the line should be visible for.

The start position is the GameObject which has this script attached.
The direction of the vector is the player.

Entering Play Mode in Unity, the Scene view will look like this:

To check if the calculation was correct, we can log the magnitude value calculated by Unity:

And as you can see, the calculated vector is exactly the same!

Moving to the target
One last thing is still missing in the behavior, the movement aspect.

We simply need to tell the GameObject which has the script to move to the calculated direction vector. To make the movement speed consistent and not slower the closer the enemy is, we Normalize the direction first.

And here is what it looks like in Unity:

That also works if the player changes the position:

Super exciting to get this to work! Well, now then player.. You aren’t save anymore from the enemy… Keep that in mind…

Oh, and before I forget it, here is the full code from todays article:

Thanks for reading this article and your time!
See you next time!

--

--

Timo Schmid
Nerd For Tech

The mission? Becoming a game developer! RPG is the dream! Writing down my journey here for me and for everyone interested. Thanks for showing interest :)