Raycast from part to players head goes through parts in the way

Hi I made this raycast cycle through all players characters in a game and shoot their heads, but when there is a wall in the way the raycast ignores this and goes through it getting to its destination anyway. How can I make the raycast stop if there is something in the way? Thanks.

local part = script.Parent

while wait(1) do
for _,v in pairs(game.Players:GetPlayers()) do
	local character = v.Character
	if character then
		
local myFirstRay = Ray.new(part.Position, (part.Position-character.Head.Position))



	local hit, position = game.Workspace:FindPartOnRay(myFirstRay, character)
	
	if hit then
		print "Ray intersected another part!"
		
local laser = Instance.new("Part")
laser.Parent = workspace
laser.CanCollide = false
laser.Anchored = true
local dist = (part.Position-character.Head.Position).magnitude
laser.CFrame = CFrame.new(part.Position, character.Head.Position)*CFrame.new(0,0,-dist/2)
laser.Size = Vector3.new(0.1,0.1,dist)
game.Debris:AddItem(laser,0.2)

	else
		print "No part found"
	end
end
end
end	
1 Like

The issue may be the direction of the ray; If you want the direction to a position from another position, you’d do: (to - from).Unit and switching it with (from - to).Unit, which is what you’re doing, will inverse the direction. Since the origin is the part’s position, if the player is right in front you and you use from - to, the direction will actually go behind the part and away from the character.

Try this:

local myFirstRay = Ray.new(part.Position, character.Head.Position - part.Position)
2 Likes

Thanks but it still shoots through objects

I’m very late to this thread, but this worked. Thank you so much!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.