How do i make a UI object follow the mouse?

I want an GUI Object to follow the mouse but i keep getting a weird offset. I don’t know why it has an offset so i can’t solve the problem.

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local camera = workspace.CurrentCamera

local Inventory = script.Parent
local Container = Inventory.Container
local Item = Container.Item

local connection = nil

local function FollowMouse()
	local mousePosition = UserInputService:GetMouseLocation()
	local x = (mousePosition.X - Container.AbsolutePosition.X) / Container.AbsoluteSize.X
	local y = (mousePosition.Y - Container.AbsolutePosition.Y) / Container.AbsoluteSize.Y
	
	Item.Position = UDim2.new(x, 0, y, 0)
	print(Item.AbsolutePosition.Y, mousePosition.Y)
end

Item.Activated:Connect(function()
	connection = RunService.Heartbeat:Connect(FollowMouse)
end)

Anything helps :pray:. I really want to solve this!!

2 Likes

Could your anchor point not be set correctly? Or does the offset increase and decrease the further and closer you get to the edge and center of the screen

2 Likes

The anchorpoint is 0.5, 0.5. It does not seem to affect the offset issue for me. The offset seems to stay the same on all positions on the screen.

1 Like

have you tried deviding it by 2?
Im not 100% sure but I think this should look something like this.

local function FollowMouse()
    local mousePosition = UserInputService:GetMouseLocation()
    local containerPosition = Container.AbsolutePosition
    local containerSize = Container.AbsoluteSize
    local itemSize = Item.AbsoluteSize
    
    local offsetX = itemSize.X.Offset / 2
    local offsetY = itemSize.Y.Offset / 2
    
    local x = (mousePosition.X - containerPosition.X - offsetX) / containerSize.X
    local y = (mousePosition.Y - containerPosition.Y - offsetY) / containerSize.Y
    
    Item.Position = UDim2.new(x, -offsetX, y, -offsetY)
-- the print statement or your further code. just add what you want
end

4 Likes

There are existing modules that are designed for dragging UI:

Do a quick Google search for some other solutions. The one linked is just the one that I use.

4 Likes

Well you can use a plugin that does it for you, to where you don’t have to reinvent the wheel. This should work for any size GUI and is fully dynamic (changing size doesn’t mess it up). Its a free plugin that just inserts the script that handles everything into the GUI component that you have selected.

2 Likes

It might be caused by IgnoreGuiInset being disabled. If you don’t want to change that property, you can do this:

Item.Position = UDim2.new(x, 0, y, 0 - 36)
2 Likes

The gui object has no offset anymore and is working as i want it to. Thank you!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.