Can anyone explain mouse.hit?

So a lot of times my game will be using mouse.hit but the dev hub has me confused can anyone explain mouse.hit but simplify it a bit or tell me the very basics? Would be appreciated heavily, thank you.

2 Likes

As stated here, this property indicates CFrame of the mouse’s position in 3D space. It can be used to create, say, a basketball to make it shoot where the mouse is pointing at. You can get the position by doing this:

local position = mouse.Hit.p
8 Likes

CFrame.p is deprecated. You should use mouse.Hit.Position instead.

7 Likes

When you access the .Hit property, it’s actually doing a raycast operation outward from the mouse and then returning the CFrame of where the ray hit (hence the name). The .Target property is similar, but returns the object it hit.


You could actually replicate this same behavior in your code:

local userInput = game:GetService("UserInputService")
local cam = workspace.CurrentCamera

-- Get mouse position:
local mousePos = userInput:GetMouseLocation()

-- Get the ray from the mouse and project it 1000 studs forward:
local mouseRay = cam:ViewportPointToRay(mousePos.X, mousePos.Y)
mouseRay = Ray.new(mouseRay.Origin, mouseRay.Direction * 1000)

-- Cast the ray:
local target, hit = workspace:FindPartOnRay(mouseRay)
16 Likes

I’m rather thick so please be tolerant but why exactly are we projecting the ray 1000 studs forwards? Also do you mind giving an example of a case that mouseray.origin is applicable to as well as why we use it in said case? Trying to understand some of the basics of mouse.hit before I go more in-depth and make this drag and drop system.

1 Like

Sorry, I probably posted too much info than needed. The 1000 studs distance is arbitrary; it’s basically how far away the ray is allowed to shoot out before coming to a stop. Making it too far can hurt performance, but you also don’t want it too short.

According to the developer page, Origin is “A CFrame positioned at the Workspace.CurrentCamera and oriented toward the Mouse 's 3D position.” In other words, imagine an arrow that sticks out from the camera and points in the direction of the mouse.

3 Likes

I don’t know if I’m 100% right here but mouseRay = Ray.new(mouseRay.Origin, mouseRay.Direction * 1000)means that it’ll create a ray casting in whatever direction the mouse is pointing at and to get the direction in the 3d space that the mouse is pointing at we use mouseray.origin which’ll tell us what direction it’s pointing at in 3d space and then we send a ray in the direction of wherever the mouse is pointed? With a limitation of 1000 studs.

2 Likes