How to make a frame follow the mouse

What I am trying to do is make a Aim Cursor follow the mouse, the reason I’m doing this is because the game would have scoping integrated in it. Im am using the following code:

local function AimFollowMouse()
	Aim.Position = UDim2.new(0, mouse.X, 0, mouse.Y)
end

Connected with a mouse.Move Event.
The aim frame is set up like so:

And this is the gameplay result:

Im thinking I have to offset the frame because it follows the mouse but with an offset. All help is appreciated.

3 Likes
local function AimFollowMouse()
	Aim.Position = UDim2.new(0, mouse.X - Aim.AbsoluteSize.X / 2, 0, mouse.Y - Aim.AbsoluteSize.Y / 2)
end
1 Like

It still follows the mouse the same way

Some of “stolen models” were used by many people and are in the toolbox, others were built originally, and all the scripts were made by myself, if your not gonna read and use your fundamentals dont say anything lol

You need to add the offset of 20 (I think) on top of the other offset that @bytesleuth mentioned. Or, you can disable the property where the ScreenGui ignores the ingame core gui.

1 Like

20 just makes it flip to the other side of the mouse and it seems that when i turn IgnoreGuiOffset it gets closer to the actual mouse which is good in this case

I forgot to mention that you only add it to the y axis and not to the x axis

1 Like

It’s your image anchor point, set it to {0.5 0.5}. Or add an offset like @bytesleuth said but like this instead

Aim.Position = UDim2.new(0, mouse.X, 0, mouse.Y + Aim.AbsoluteSize.Y / 2)
1 Like

Ok so i kept the anchor point to 0.5,0.5 and used ur code and it was aligned on the x axis but was still above it, when i added 20 offset to the Y axis it was closer but still not aligned

I said or, either set the anchor point to 0.5 0.5 OR do this:

Aim.Position = UDim2.new(0, mouse.X, 0, mouse.Y + Aim.AbsoluteSize.Y / 2)

If you are using the first case, don’t add the offset.

1 Like

You can do this and just set AnchorPoint to 0,0

1 Like

You and @bytesleuth code both align to the x axis only the Y isnt aligned though

I ended up doing this:

Aim.Position = UDim2.new(0, mouse.X, 0, mouse.Y + Aim.AbsoluteSize.Y + 34)

Is there a better way to calculate this rather than adding a random offset and it working

1 Like

Hey there, unfortunately, there isn’t a way to calculate this number, as 34 is simply the pixel size of the Roblox topbar. I do however recommend that instead of you adding this number in your calculations, change the ScreenGui’s ScreenInsets property None.
This will make Roblox ignore the topbar, and leave you with the same result.

1 Like

Technically this is off by 2 pixels the topbar is 36 pixels tall. You can get this reliably by from GuiService GetGuiInset

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