How to get mouse position

Hello, I’m trying to get the 3D mouse position with this script

	local mouse = game.Players.LocalPlayer:GetMouse()
	local mouseX = mouse.X  
	local mouseY = mouse.Y 
	local cam = workspace.CurrentCamera
	local ray = cam:ScreenPointToRay(mouseX, mouseY) 
	return ray.Origin

However the ray.Origin it returns seems to be incorrect:

what am I doing wrong and why is it incorrectly getting the mouse pos?

The origin of any of the camera’s world-to-ray functions is the camera’s CFrame itself, you’re not seeing incorrect behaviour here. What you’re going to want to do instead is perform an extended-length raycast derived from the ray returned by ScreenPointToRay and use RaycastResult.Position (if one exists) to get the point of intersection from the raycast. Docs for example of extending a unit ray (this can be plugged into WorldRoot:Raycast instead of the Ray datatype constructor).

I figured it out on my own and I just wanted to say your explanation would have been confusing if I used it.

To anyone who needs help with raycast, simply use

local ray = workspace:raycast(origin, direction, params)

The ray holds a lot of information but most importantly the position. You can get the position like this:

ray.Position

I mean that’s pretty much what I explained. What confuses you about the explanation?

  • The origin of a camera ray is the camera’s CFrame. You said this is wrong, it isn’t.
  • You can plug the origin and direction received from a camera world-to-ray function into WorldRoot:Raycast (as it expects an origin and direction).
  • The aforementioned ray should have its length extended (camera ray functions return a unit ray) to cast to a point in the world.
  • From the raycast’s result, Position is the point of intersection (the position at which the ray hit an object, if it did hit one).

You’re right on how to raycast but I don’t think your solution actually answers your problem of translating the mouse into a 3D space, it’s just reiterating what’s already in the docs (which, if you were confused on how to raycast, you likely should’ve read first instead).

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