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

How do I create a ray shooting downwards from my character's leg?

I'm trying to create a ray shooting downwards from my character's leg. I will later implement this into an NPC to prevent it from walking off the side of a cliff, but for now I'm just using my own character.

The problem is, I do not know how to get the ray to shoot straight down. I'm still pretty bad at vector math, but I thought if I were to take the leg's position and subtract 50 from the y, it should shoot down from the leg, because the leg's position just lost 50 studs of height. It didn't work. The ray did shoot downwards, but at an angle, not straight down.

The following code is in a LocalScript in StarterGui. No errors are in the output. The line you need to focus on is line 7.

local plr = game.Players.LocalPlayer
	repeat wait() until plr.Character
local chr = plr.Character

while true do
	wait(2)
	local ray = Ray.new(chr["Left Leg"].Position, chr["Left Leg"].Position - Vector3.new(0,50,0))
	local hit,position = workspace:FindPartOnRay(ray)
	print(hit)
	
	--Draw the ray for easy testing.
	local distance = (position - chr["Left Leg"].Position).magnitude
	local rayPart = Instance.new("Part", workspace)
	rayPart.Name = "RayPart"
	rayPart.BrickColor = BrickColor.new("Bright red")
	rayPart.Anchored = true
	rayPart.CanCollide = false
	rayPart.FormFactor = "Custom"
	rayPart.Size = Vector3.new(0.2, 0.2, distance)
	rayPart.CFrame = CFrame.new(position, chr["Left Leg"].Position) * CFrame.new(0, 0, -distance/2)
end

2 comments

0

Perhaps the reason why the ray's shooting at an angle is because the legs themselves are angled when the NPC is walking.

0

It did the same while I was standing still. It would always angle slightly to the left. Walking and standing made absolutely no difference.

1 answer

✓ Accepted answer

You don't need to bother with casting the ray relative to orientation of the leg, and neither the position nor orientation of the leg have any bearing on the direction that you want the ray to face.

All you need to set for the direction is (0,-1,0) - parallel and in the same direction as the negative y-axis.

local ray = Ray.new(chr["Left Leg"].Position,  Vector3.new(0,-1,0))

Edit: Note that this Ray will only have a magnitude of 1, a length of 1. If you want to make it longer just multiply the direction vector by the length that you want it to have.

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