#Making a UI or Frame rotate to the Mouse Position on the screen

2 messages · Page 1 of 1 (latest)

swift nebula
#

I would solve this by visualizing a triangle that is created between your Frame and the current mouse AbsolutePosition. We can then use the inverse tangent of that triangle's X and Y sides to return the angle at which we need to rotate our Frame.

local Frame = script.Parent
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local RunService = game:GetService('RunService')

RunService.RenderStepped:Connect(function() -- Binded to the client's frames to prevent stuttering
    
    local MousePosX = Mouse.X -- Mouse's X position
    local MousePosY = Mouse.Y -- Mouse's Y position
    local FrameX = Frame.AbsolutePosition.X -- UIObject's X position
    local FrameY = Frame.AbsolutePosition.Y -- UIObject's Y position
    local DifX = MousePosX - FrameX -- Base of our triangle
    local DifY = MousePosY - FrameY -- Height of our triangle
    local Angle = math.deg(math.atan(DifY/DifX)) -- Inverse tangent of height over base, converted to degrees
    Frame.Rotation = Angle -- Rotate frame to match calculated angle
end)
swift nebula
#

To accomplish this we can continue to think about our triangle - we essentially want to position the UI part somewhere along the hypotenuse of our visualized triangle at a specific offset from our origin point. To do this we can use some more trigonometry (SOH-CAH-TOA) and a little bit of algebra to identify this point. This does create an issue because negative numbers in Sine and Cosine functions produce a positive value when we want to keep the negative. We can bypass this by using an if statement to check if we want the negative or positive value. Finally, we can use the same angle calculation as before so that the UI object continues to point to the mouse.