How can I calculate an angle on the screen with the position of the mouse?

How can I calculate the amplitude of this angle made by two vectors?
The red line is a vertical vector and green is a vector that ends up in the mouse position.

3 Likes

From what I can tell, you are looking for the angle, clockwise from the upwards vertical angle. The variables cx and cy are for the center position. If the position is already relative, then you can just remove the -cx and -cy.

Radians

-math.atan2(y - cy, x - cx) + math.pi*.5

Degrees

math.deg(-math.atan2(y - cy, x - cx))+90

Assuming you want the angle going clockwise,

local greenVector = mousePos - centrePos

can get the centrePos via camera.ViewportSize/2 (ignoring gui inset applied by the top bar)

Then, if you want -180 < angle <= 180,

local angle = math.deg(math.atan2(x, -y))

where x is greenVector.X and y is greenVector.Y

Or, if you want 0 <= angle < 360

local angle = math.deg(math.atan2(x, -y))
angle = angle < 0 and 360 + angle or angle --(adds 360 degrees when angle is negative)
6 Likes

This is exactly what dot product does for you:

math.acos(Vector1.Unit:Dot(Vector2.Unit))

This would give you an angle (in radians) between two unit vectors, with (0,0,0) as the origin.
If your origin is off-center, you can simply subtract that defined origin from the two vectors, and then get the dot product:

Vector1 = Vector1 - Origin
Vector2 = Vector2 - Origin
2 Likes

Thanks for all the answers. This forum is awesome!!

2 Likes