Get Mouse Position(X, Y, Z) On The Screen/Camera In A RunService Loop Without Player:GetMouse()

I don’t want to use Player:GetMouse() since it seems to be advised against using.

Though using UserInputService is a bit difficult as I need this run in a loop and the best I can seem to do with UserInputService is use the UserInputService.InputChanged event and get the InputObject.Position.

If I do this though and the character moves while the mouse doesn’t, the 3D position that was last updated for the mouse relative to the camera/screen would be wrong, wouldn’t it?

I was thinking of using UserInputService:GetMouseLocation() however that only returns a Vector2

Is this possible to do with UserInputService or do I have to use Player:GetMouse()?

I Believe this Could Help you out!
https://developer.roblox.com/en-us/api-reference/property/Mouse/Hit

It could probably work, however I want to avoid using the Mouse object! Thank you though

1 Like

No problem at all, I am quite curious to find out if there any better way, ill stay tuned…

I managed to figure things out!

I used UserInputService:GetMouseLocation() as originally planned, then used Camera:ViewportPointToRay() and inputted the X and Y values from GetMouseLocation, then you can simply use the Origin value from ViewportPointToRay :slight_smile:

local Distance = 20
local Part = Instance.new("Part")
Part.Parent = Character
Part.CanCollide = false
Part.Transparency = 1
Part.Size = Vector3.new(1,1,Distance)

RunService.RenderStepped:Connect(function()
	local MouseScreenPointPos = game:GetService("UserInputService"):GetMouseLocation()
	local ViewportMouseRay = Camera:ViewportPointToRay(MouseScreenPointPos.X, MouseScreenPointPos.Y)

	Part.Position = ViewportMouseRay.Origin
	Part.CFrame = CFrame.lookAt(ViewportMouseRay.Origin, ViewportMouseRay.Origin + ViewportMouseRay.Direction * 2)
	Part.CFrame = Part.CFrame * CFrame.new(0,0,-Distance/2)
end)

Result:
Woowoo

3 Likes