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

I can't Detect If a player is near me with RayCasting?

Basically, I am trying to detect, if someone is near me and if im facing them. The script is written down below, but I get an error when i press the R key, which is: ** Parent is not a valid member of Ray** on this line

	if theRay.Parent:FindFirstChild("HumanoidRootPart") then

I don't understand what am I doing wrong, anyone could help, first time using ray casting

game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function(player)
	local Character = player.Character
	
	local theRay = Ray.new(Character.HumanoidRootPart.Position, Character.HumanoidRootPart.CFrame.LookVector * 10)
	if theRay.Parent:FindFirstChild("HumanoidRootPart") then
		theRay.Parent.Humanoid:TakeDamage(20)
	end
end)

2 answers

A ray does not have a parent until it hits something. Remember to check whether the ray has a parent too before checking whether it's parent has a humanoid root part. Here's your edited code:

game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function(player)
    local Character = player.Character

    local theRay = Ray.new(Character.HumanoidRootPart.Position, Character.HumanoidRootPart.CFrame.LookVector * 10)
    if theRay.Parent and theRay.Parent:FindFirstChild("HumanoidRootPart") then
        theRay.Parent.Humanoid:TakeDamage(20)
    end
end)

2 comments

0

Parent is not a valid member of Ray

0

hmm thats weird

You forgot to add FindPartOnRay/Raycast Raycasting is the new version, but I find FindPartOnRay easier.

As the dev forum includes, it requires 2 arguments.

local character = game.Players.LocalPlayer.Character
-- Get the head
local head = character:FindFirstChild("Head")
-- Build a ray in the direction the head is facing
local origin = head.Position
local lookDirection = head.CFrame.LookVector
local ray = Ray.new(origin, lookDirection * 500)
-- Raycast, ignoring the player's character
local hitPart, hitPosition = workspace:FindPartOnRay(ray, character)
if hitPart then
	print("Hit part: " .. hitPart:GetFullName())
else
	print("Did not hit part")
end

Rays will always return HitPart, HitPosition, HitNormal, etc.

If you'd like to add an ignore list where the ray can pierce through, read the FindPartOnRayWithIgnoreList documentary.

1 comment

0

I am consentaly Getting the "Did Not Hit part" even when I'm close to the Character

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