Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to get mouse position using mouse.Hit?

Asked by
bdam3000 125
3 years ago

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

Log in to vote
0
Answered by 3 years ago

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
0
Thanks a lot! This answer really goes in depth and I think I understand more. bdam3000 125 — 3y
Ad

Answer this question