Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to position a frame at the mouse's location?

Hello!

I have recently been trying to position a frame wherever the player clicks Here's what I did:

OBJECT HIERARCHY:

  • StarterGui/ScreenGui

  • StarterGui/ScreenGui/Button

  • StarterGui/ScreenGui/Button/LocalScript

  • StarterGui/ScreenGui/Button/Frame

Then I tried two methods... First one was relatively simple:

local button = script.Parent
local frame = button:WaitForChild("Frame")
local userInputService = game:GetService("UserInputService")

button.MouseButton1Click:Connect(function()
	local pos = userInputService:GetMouseLocation()
	frame.Position = UDim2.new(0, pos.X, 0, pos.Y)
end)

The achieved result was this

That didn't work for some reason... So I tried a little different approach:

local button = script.Parent
local frame = button:WaitForChild("Frame")
local userInputService = game:GetService("UserInputService")

button.MouseButton1Click:Connect(function()
	local pos = userInputService:GetMouseLocation()
	local relativePosition = pos - frame.Parent.AbsolutePosition
	frame.Position = UDim2.fromOffset(relativePosition.X, relativePosition.Y)
end)

I got the exact same result. Both cases, the frame was position well above the click.

I don't understand why.

Any help would be appreciated.

Kind regards,

Rod455

1 answer

I fixed it! I was using the first script and all I did was change a Udim2 value and make sure that the frames anchor point is 0.5, 0.5 ~ Here's the script:

local button = script.Parent
local frame = button:WaitForChild("Frame")
local userInputService = game:GetService("UserInputService")

button.MouseButton1Click:Connect(function()
    local pos = userInputService:GetMouseLocation()
    frame.Position = UDim2.new(0, pos.X, -0.2, pos.Y) 
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.