What I want to do is make a frame extend from the center of the screen to the mouse’s position. The problem is, my current calculation for rotation and magnitude between the two points is inaccurate for some reason and I am unable to figure out why and how to fix it.
Code:
local uis = game:GetService("UserInputService")
local camera = workspace.CurrentCamera
local gui_inset = game:GetService("GuiService"):GetGuiInset()
local center = script.Parent.Center
local line = script.Parent.Line
uis.InputChanged:Connect(function(input,gp)
if (gp) then return end
if (input.UserInputType ~= Enum.UserInputType.MouseMovement) then return end
local viewport_size = (camera.ViewportSize-gui_inset)
local mouse_pos_scale = Vector2.new(input.Position.X/viewport_size.X,input.Position.Y/viewport_size.Y)
local center_pos_scale = Vector2.new(center.Position.X.Scale,center.Position.Y.Scale)
local difference = (mouse_pos_scale-center_pos_scale)
local rotation = math.atan2(difference.Y,difference.X)+(math.pi*0.5)
local size = UDim2.fromScale(line.Size.X.Scale,difference.Magnitude)
local position = UDim2.fromScale(center_pos_scale.X+(difference.X*0.5),center_pos_scale.Y+(difference.Y*0.5))
line.Position = position
line.Size = size
line.Rotation = math.deg(rotation)
end)
Yes I have searched the DevForum and other websites like stackoverflow, all of them showed the same method as I used in the script above, but it isn’t accurate for some reason.
Screenshot:
But it starts getting more and more accurate as I start moving my mouse towards 0 degrees or 180 degrees from the center. At 90 or -90 degrees (x axis), rotation is accurate but not the magnitude. At 180 or 0 degrees the rotation and magnitude are both accurate, any other angle both of them are inaccurate.
Please someone answer how to fix this it will be appreciated because at this point I am clueless about why this is happening.
Both Frames anchor point is (0.5,0.5)
, and no the mouse position is not wrong, I tested it by positioning a frame on the mouse position and it worked fine.