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

How do i get the mouse position? [SOLVED]

Okay, I've been working on a game, And i want to make a gui that follows your mouse, but i cant get the script to work

while true do
	game.StarterGui.MouseGui.Frame.Position = mouseX
end

The error is on line two, It says mouseX does not exist [simplified] and other complicated stuff

1 answer

✓ Accepted answer

First of all, if there is an infinite loop without a form of a delay, it will crash your game. Change true into wait(). wait() is 0.299999999999 seconds long.


Gui's don't use "Position" like how parts do. They do something called "UDim2".

mainFrame.Position = UDim2.new(0.25, 0, 0.25, 0) --Changes "MainFrame's position to 0.25 scale to 0.25 scale."

Gui's position isn't close to Vector3.


The next part is mouseX. First we need to find mouse which is in a player. In 2010 they inserted a new method called :GetMouse() so, because this is a local script, we can use something called LocalPlayer. In order to do this we need to go into game.Players. So this is how we could get the mouse from LocalPlayer.

local player = game.Players.LocalPlayer --This is the player
local mouse = player:GetMouse() --This is the mouse.

The last part is the "X" part of mouseX. X is a property of mouse so we need a dot before it. It should look like

mouse.X

Now, with mouse.X we can only follow the X axis. We need to follow the Y axis also.

mouse.Y

Now if we add all this together we should get:

local mouse = game.Players.LocalPlayer:GetMouse()
while wait() do
	script.Parent.Position = UDim2.new(0, mouse.X,0, mouse.Y)
end

Let's say the thing that is following your gui is too big, so the mouse goes off your gui, just subtract a certain amount. For example

local mouse = game.Players.LocalPlayer:GetMouse()
while wait() do
	script.Parent.Position = UDim2.new(0, mouse.X-65,0, mouse.Y-65) --Notice the "-65"s. This could be any number.
end

I hope this helps!

7 comments

1

There's also a Moved event that you could use instead of a loop (or you could use mouse.Moved:wait() I suppose). (Excellent answer!)

0

Okay, thanks for the tip!

0

Thanks! This was really helpful! I'll try it out.

0

@bluetaslem get 1337 rep .-.

0

^I'll take a screenshot when he gets 1337 rep.

0

^ lol okay (sorry about all of the late replies but i forgotht about dis site

0

@ FunzreyAlt , I didn't take a screen shot of him having 1337 rep, I did take a picture of him having 1234 reputation, lol.

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