How to rotate an Frame around a fixed point so it follows the mouse cursor?

What do you want to achieve?


What solutions have you tried so far?

I tried to search for codes outside the Lua language, however, most of them used 3D, in my case I need something in 2D (GuiObject)

2 Likes

You can do that using two vectors and simple math: one vector is the vector starting at the center of the Frame and ending at the position of your mouse, the second vector is a vertical vector. You calculate the angle between these vectors using dot product
image
This formula only gives you the acute angle between these vectors, that’s why we have to do a fix and make the angle negative when the mouse is on the right side relatively to the center of the frame.
Having that said we implement the algorithm in code:

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local frame = script.Parent
local verticalVector = Vector2.new(0, 1)
local rs = game:GetService("RunService")

rs.Stepped:Connect(function()
	local framePosition = frame.AbsolutePosition + frame.AbsoluteSize / 2
	local mousePosition = Vector2.new(mouse.X, mouse.Y)
	
	local lookvector = (mousePosition - framePosition).unit
	local angle = math.acos(verticalVector:Dot(lookvector))
	if framePosition.X < mousePosition.X then
		angle = -angle
	end
	
	frame.Rotation = math.deg(angle)
end)

With the following setup to make it easier to understand:
image

4 Likes