Why won't my raycasting script work?

Whenever I run this script, the ray only casts in one direction instead of casting toward the player.

wait(5)
while wait() do
for i,v in pairs (game.Players:GetChildren()) do
	local char = v.Character
		local hrp = v.Character.HumanoidRootPart
		local casterpos = game.Workspace.caster.Position
	local explosionRay = Ray.new(casterpos, hrp.Position)
	local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(explosionRay, {game.Workspace.caster})
	if hit then
		print(hit.Name)
	end
	end
end

Why would this happen, and how could I fix this? Thank you.

1 Like

Try

Ray.new(casterpos, hrp.Position-casterpos)
2 Likes

That worked, thank you for the help. However, I have a question. Why did that work?

The second parameter of ray.new is a direction, so you need to get the position of the goal relative to the origin

You do that using the formula

goal-origin

Which is a pretty standard formula which just gets the displacement(direction) between two numbers, like how doing 5 - 3 gets you 2, because 5 is 2 up from 3

oh okay, thank you for explaining that to me

1 Like