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

How to get mouse position using mouse.Hit?

This is my LocalScript:

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local mousepos = mouse.Hit.p

while true do
	print(mousepos)
	wait(1)
end

It should print the position of the mouse every second, but it prints the same position every time. Probably an easy fix, but please help.

1 answer

✓ Accepted answer

Storing Variables

A common mistake many developers make is they store a variable rather than grab the latest updated value. Here is an example using a BoolValue.

local boolValue = Instance.new('BoolValue', workspace)
boolValue.Value = true

local x = boolValue.Value
--since boolValue.Value is true, x is true

print(x)
print(bool.Value)

boolValue.Value = false
--what if we change the value?
--well, x is stored and will stay true
--we can check this interaction by printing

print(x)
print(bool.Value)

Output:

true

true

true

false


Correction

This same principle applies to your problem. You are storing Mouse.Hit.p as a variable when you actually want to get the updated version. An easy fix would be just to put mousepos inside your loop.

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

while true do
	local mousepos = mouse.Hit.p
	print(mousepos)
	wait(1)
end

1 comment

0

Thanks a lot! This answer really goes in depth and I think I understand more.

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