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

Issue with Raycasting?

I'm trying to have this script print the name of wherever parts my character's torso is facing, but it just keeps on returning Nil... Why?

while true do
	wait()
	local Torso = game.Players.LocalPlayer.Character.Torso
	local Humanoid = game.Workspace:WaitForChild(game.Players.LocalPlayer.Name).Humanoid
	--game.Workspace:WaitForChild(game.Players.LocalPlayer.Name).HumanoidRootPart.Velocity = Vector3.new(Torso.Velocity.X, Humanoid.JumpPower * 1.2, Torso.Velocity.Z)--hit.Position * CFrame.new(0,100,0)
	local start = Vector3.new(Torso.CFrame)
	local lookAt = Vector3.new(Torso.CFrame.lookVector)--(Torso.CFrame * CFrame.new(0,-1,0))
	local ray = Ray.new(start, 999*(lookAt - start).unit)
	local part, endPoint = workspace:FindPartOnRay(ray, game.Players.LocalPlayer.Character)
	if part~=nil then
		print(part.Name)
	else
		print("nil")
	end
end

1 comment

0

okay, I hadn't noticed how much was wrong with this... You should review how to use Vectors correctly.

1 answer

✓ Accepted answer

You already have Vector3s

Your definition of lookAt and startAt is wrong. lookVector and Position are already a Vector3. (Use Position instead of CFrame)

Passing it to Vector3.new does not do anything useful (and in fact will ignore it and just return (0,0,0)).

    local start = Torso.Position
    local lookAt = Torso.CFrame.lookVector

Making the right Ray

length

From the Wiki article

The length of the direction vector is important - parts further away than its length will not be tested.

The length of your ray is 1 (it's a unit vector).

Multiply the direction part by 999:

	local ray = Ray.new(start, 999*(lookAt - start).unit)

direction

However, you're taking the direction from a position to something next to the origin. lookAt isn't a point in space. It's a direction. Just multiply it by 999:

	local ray = Ray.new(start, 999 * lookAt)

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