Mouse.Hit exclude certain parts

I know that Mouse.Hit returns a CFrame of where a ray from the mouse hits an object/part in the game. My question is, is there any way to have the ray go through certain parts and ignore others that I can decide in scripts, or is there another way of doing it? So if I point my mouse at a part of a certain name with a part behind it the Mouse.Hit ray will ignore the first part and return the position of the intersection with the second. Sorry if this is a dumb question but I can’t find any solutions anywhere.

3 Likes

Yes there is! It’s called Mouse.TargetFilter. If you want to have multiple of Instances then make a folder with the instances under it and index it to the folder, but I believe there should be an IgnoreList like what Raycast has.

If you’d like to push this feature out then you should refer to this:

6 Likes

The Mouse API is considered legacy and has been largely superseded by better alternatives, such as UserInputService and ContextActionService.

Instead of Mouse.Hit, you could use this function, which takes an ignore list. Its second result (a Vector3) is the position in 3D space that the mouse hits:

local workspaceService = game:GetService("Workspace")
local userInputService = game:GetService("UserInputService")

local currentCamera = workspaceService.CurrentCamera

-- Instance<BasePart>?, Vector3, Vector3, EnumItem<Material> getMouseHit(table ignoreList)
local function getMouseHit(ignoreList)
    local mouseLocation = userInputService:GetMouseLocation()
    local viewportPointRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
    local extendedRay = Ray.new(viewportPointRay.Origin, viewportPointRay.Direction * 1000)
    
    return workspaceService:FindPartOnRayWithIgnoreList(extendedRay, ignoreList)
end

For example:

local _, position = getMouseHit({workspaceService.SomePart, localPlayer.Character})
print(position)
28 Likes

Exactly what I’m looking for. Thanks, I’ll try and not use the Mouse API as well.

1 Like

Thanks, that’s what I need. I’ll try and avoid Mouse in future as well, I didn’t know that.

It turns out Camera:ViewportPointToRay should be used over ScreenPointToRay for this, otherwise the GUI inset is accounted for. I’ve edited the code appropriately.

6 Likes