How to make a 2D ui element face the mouse? (Probobly a math problem)

I want to make a 2D UI element that will orientate to face the mouse. Does anyone know what I would do to achieve something like this?

2 Likes

What exactly do you mean? Like for example, an arrow that will rotate to point directly at the mouse?

You can get the angle in radians between two 2D vectors with math.atan2(difference.Y, difference.X) (yes, the terms are reversed on purpose).

So if you have two Vector2’s indicating the position of the mouse and the position of a “compass” pointing towards the mouse, you can control the “compass” like so:

local difference = (mousePos - compassPos)
local angle = math.atan2(difference.Y, difference.X)
compass.Rotation = math.deg(angle) --Rotation is in degrees

You should probably use GuiObject.AbsolutePosition to get their absolute coordinates rather than relative to their parent. You’ll also want to make sure the AncorPoint of the compass is set properly.

8 Likes

That solved it. Sorry for not making a reply