Running into issues with raycasting

I have this script:

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
mouse.Button1Down:Connect(function()
	if plr.Character ~= nil then
		if mouse.Hit ~= nil then
			local position = mouse.Hit.p
			local origin = plr.Character.LeftHand.Position
			local ray = Ray.new(origin, position)
			local hit, hitposition = game.Workspace:FindPartOnRayWithIgnoreList(ray, plr.Character:GetChildren())
			if hit then
				if hitposition == position then
					print("A part has been clicked")
				end
			end
		end
	end
end)

and I would like to find out if the player’s mouse is on a part every time the player left clicks using a ray cast that casts from the player’s left hand to the position that the mouse is in. I would like the script to tell me if the mouse position is on a part, instead of intersecting one. Nothing appears in the output when I click a part, though. Is there a better way to do this? What am I doing wrong?
Please lmk if anything is unclear since this is pretty hard to explain.

The position is the where the mouse is while the hitposition is the position of the hit(part)

1 Like

Maybe try checking if the hitposition is equal to hit.position

1 Like

The two arguments for a ray is origin and direction. You’re setting direction to a position, so the ray won’t work as you want.

To get a direction vector, you can just do local direction = position - origin, and create the ray as local ray = Ray.new(origin, direction)

Also, for the Ray’s IgnoreList, you can use {plr.Character} to ignore the player instead.

2 Likes