Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to find distance from closest part infront of torso using rays?

I'm trying to make a ray coming from the player's torso (humanoidrootpart for r15 support), going forward in the direction it's facing to find how far the part that's closest in-front of it is.

I made this script but for some reason it doesn't properly do what I want. (local)

game:GetService("RunService").RenderStepped:connect(function()
	local ray = Ray.new(plr.Character.HumanoidRootPart.Position, plr.Character.HumanoidRootPart.CFrame.lookVector)
	local part, position = workspace:FindPartOnRay(ray, plr.Character, false, true)

	local distance = (plr.Character.HumanoidRootPart.Position - position).magnitude
	print(distance)
end

Anyone have any idea what the problem is?

1 answer

✓ Accepted answer

When you give the ray a direction you must also give it a length (for hit detection). When you think about it, right now you simply create a vector with a length of 1 stud, which obviously won't hit anything!

Try this:

local ray = Ray.new(plr.Character.HumanoidRootPart.Position, plr.Character.HumanoidRootPart.CFrame.lookVector*500)

1 comment

0

Thank you!

This discussion is preserved as it was. New answers, comments, and votes are closed.