Calculating Relative Mouse Angles in JavaScript Using atan2()
written by Idriss Douiri
3 min read
Ever wondered how to rotate an object based on the mouse angle, or detect the direction where the player shoots a bullet, or maybe something more creative for your next User Interface?
this tutorial will open so many possibilities for you to explore by explaining step by step how to track the mouse angle or any points in space.
absolute angle
Let’s start simple and see how can we get the absolute angle from the origin (0, 0) i.g., the top left corner of the screen.
Before we can calculate the angle we need to keep track of the mouse position on the page, let’s set an event listener on mouse move and store the position:
addEventListenner("mousemove", e => {
const mouseX = e.pageX
const mouseY = e.pageY
})
Now that we have the mouse position we can visualize it as follows:
You can see where this is going, we got a perfectly perpendicular right angled triangle, and working with triangles involves trigonometry, so we need to find which function can give us the angle based on the data we have, and this function is tangent.
tanθ =
this function will give us the tangent of the angle, but we need the angle so we can use the inverse function of the tangent or arctangent of y / x to get the angle:
const angle = Math.atan(mouseY / mouseX)
Great! We’ve got the angle, but there is an issue with this implementation because atan() returns a value between which is half turn but we need the full turn, the reason for that is beacause can return the same output with two different inputs (e.g., ) so the function can’t give you the right angle without knowing which axis is negative and which one is positive.
Solving this problem is simple, just switch to the atan2() function and pass y and x separately as its parameters so that the function can then decide which quarter you are working on.
Math.atan2(mouseY, mouseX)
Relative Angle
Calculating the angle relative to another point is quite the same. let’s say we have a point p1(2, 3) and the mouse is currently at p2(5, 1) as shown below:
we can get a vector from p1 pointing towards the mouse p2 by subtracting p1 from p2:
p2 - p1 = =
As you can see we’ve got another right-angled triangle to work with and get the angle in the same way,
const dy = mouseY - p1.y
const dx = mouseX - p1.x
const angle = Math.atan2(dy, dx)
radians to degrees
These functions return the angle in radiant which might be hard to read and not human-friendly but its how you will work behind the seen, however, if you want to display the angle you probebly want to convert it to degrees before as we are used to them, and to do that just apply this formula:
const degrees = angle * 180 / Math.PI
examples
See the Pen eyes following the mouse by Driss (@driss-d) on CodePen.
example 1: Eyes looks towards the mouse.
See the Pen shooter by Driss (@driss-d) on CodePen.
example 2: player shoot bullets on click.