Math in Unity - Tracking the mouse cursor

Wanna play cat and mouse?

Timo Schmid
Nerd For Tech
2 min readJun 16, 2021

--

Another horrible pun to start the article. Nice!

Anyways, you might have played some games where some objects are always looking at the mouse pointer. This can be used for various reasons actually. Just for fun, for making the background details even more detailed, to horrify the player by constantly looking at his cursor, to make point-and-click games more detailed, …

There really are many use-cases for that. Let’s implement that today. You will be surprised, but we already know the basics of doing that. Remember yesterdays article?

I. The objective
Todays objective is that the capsule will keep track of the mouse pointer and update its rotation accordingly.

II. Crating the logic for the objective
We already talked about the mathematical aspects yesterday, so we don’t need to discuss it here again. Just remember that we need the inverted tangents function.

Let’s break down what we want to do:

  • We need to calculate the direction Vector.
    This time, the target is the mouse pointer and not a GameObject.
  • An angle is needed, so we calculate it as well
  • The angle shall be converted into degrees
  • Update the rotation of the capsule with the Euler angles

This will bring us up the following code for calculating the direction:

The rest stays the same as yesterday:

III. The working end result
Running this code in Unity will look like this:

Now the mouse cursor is also tracked. Man, no privacy here anymore…

Thanks for your time and interest!
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 :)