Raycasting mouse position

Hello!
I want to raycast the mouse position but sometimes it doesn’t find anything when I move the mouse over a part

`Mouse.Button1Down:Connect(function()

local mousePosition = UIS:GetMouseLocation()

local unitRay = Camera:ScreenPointToRay(mousePosition.X, mousePosition.Y)

local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {workspace.Baseplate, Player.Character}
rayParams.FilterType = Enum.RaycastFilterType.Blacklist

local rayResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * 500, rayParams)

if rayResult then
	print(rayResult.Instance.Name)
	local Part = Instance.new('Part')
	Part.Parent = workspace
	Part.CFrame = CFrame.new(unitRay.Origin, unitRay.Direction)
	Part.CanCollide = false
	Part.Anchored = true
else
	print('part not found')
end

end)`

Video

3 Likes

Maybe this would help game.Players.GetMouse().Position

Adding on to this, you can use the function ScreenPointToRay().

Tell me what your trying to do? a building system?

I’m already using it.
Woodx I want to make a raycast using mouse position to detect whenever there is a part where the player clicks (I know there are easier ways to do this but I want to use the raycast)

raycasting seems like a waste of time and resources just use Mouse.Target

what I need is the direction, cuz of this I used raycast

Use the following for the mouse, I think this would be a improvent and it is also better to use this for other aspects:

local Players = game:GetService("Players")
local localPlayer = Players.LocalPLayer

local mouse = localPlayer:GetMouse()

mouse.Button1Down:Connect(function()
    local mouseHitCFrame = mouse.Hit --Now use this for the raycast
end)

Hope this helped you! :slight_smile:

Sources:
https://developer.roblox.com/en-us/api-reference/class/Mouse

1 Like

Also, if you want to cast the ray from the players head or hand or idk where, use this.

local origin = localPlr.Character.Head.Position
local direction = mouse.Hit
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {workspace.Baseplate, Player.Character}
rayParams.FilterType = Enum.RaycastFilterType.Blacklist

local result = game.Workspace:Raycast(origin, direction, rayParams)
3 Likes