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)
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
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
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.