Search code examples
luaroblox

How to find the X, Y, Z of the mouse without clicking?


I've been searching for a way to get the coordinates of the mouse so I can teleport a part to the mouse for my game. All I have found is GetMouse() which I don't really understand.

Player = game.Players.LocalPlayer
Mouse = Player:GetMouse()
MousePos = Mouse.Hit
print (MousePos)

Solution

  • Alright, well first off I'm assuming your code is in a localscript (that's how it should be). ':GetMouse()' simply gets the player's mouse. The mouse has different properties, and events.

    You can get the CFrame of the mouse by doing:

    local MouseCFrame = Mouse.Hit
    

    CFrame values contain more than just the position of the mouse in real world space though. CFrame values contain position, and rotation. We can get the position by doing:

    local MousePosition = MouseCFrame.p
    

    We use the 'p' property of a CFrame value to get the position of that CFrame value. Quite useful. So, your final code is:

    local Player = game.Players.LocalPlayer -- Also, I noticed you weren't using 'local' to define your variables. Use that, as it sets the variable apart from a global variable.
    local Mouse = Player:GetMouse()
    local MouseCFrame = Mouse.Hit
    local MousePosition = MouseCFrame.p
    print (MousePosition)
    

    Hope I helped! :)