UserInputService version of Mouse.Hit

I am trying to pass the Vector3 position of the mouse from the client to the server. I dont want to use the Mouse object from the player since it has been “superceded” by UserInputService.

My basic problem is, I can’t find anything that replaces the Mouse.Hit property, I tried InputObject.Position but this is actually the mouse’s screen position (x and y only) rather than the 3D world position (x, y, AND z).

Here’s the code I currently have (using input.Position):

UIS.InputBegan:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		InputEvent:FireServer('MouseDown', input.Position)
    end
end)

Again, to reiterate, I know that I could use Mouse.Hit.Position for this. I am trying to avoid using the Mouse object.

Input position is the mouse position on the use screen, but with this position you can find the world mouse position by using the function of camera ScreenPointToRay and ray casting!

Like that:

local UserInputService = game:GetService("UserInputService")


local mousePosition = Vector.new()

local RAY_DISTANCE = 100

function MouseRay(filterTable, filterType)

	local rayData = camera:ScreenPointToRay(mousePosition.X, mousePosition.Y, 0)

	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = filterTable
	raycastParams.FilterType = filterType

	return workspace:Raycast(rayData.Origin, rayData.Direction * RAY_DISTANCE, raycastParams)
end


local function InputChanged(input, gameProcessed)
    if input.UserInputType == Enum.UserInputType.MouseMovement then
       mousePosition = input.Position
  end
end

UserInputService.InputChanged:Connect(InputChanged)

5 Likes

Thanks, more complicated than I was hoping for but always good to learn something new!

1 Like