Raycasting problems

this thing has been annoying me for a while now. so basically, i have a function which uses a raycast to see if there is a part is blocking the NPC from the player. however, despite there being a clear wall in the way, the function returns true? here’s my code:

I can immediately see an issue here

if status == "Tracking" or "Wandering" then

Lua/Luau treats the or like this

if "Wandering" then

Instead of

if status == "Wandering" then

And because a string is never nil or false, Lua always sees it as true and runs the code in the if statement. To fix it, you can just add a status ==

if status == "Tracking" or status == "Wandering" then
1 Like

Alright, although that DID turn out to be an issue, it still didn’t fix the original problem.

1 Like

You should REALLY clean up your if statements, it’s so flippin confusing!

if status == "Tracking" or status == "Wandering" then
    if dotProduct < -0.2 and rayResult == nil then
        if debugging then
            print("target found while tracking or wandering")
        end
        
        return true
    else
        if debugging then
            print("target not found while tracking")
        end
        
        return false
else
    if rayResult == nil then
        if debugging then
            print("saw target")
        end
        
        return true
    else
        if debugging then
            print("target not visible")
        end
        
        return false
end

Now, replace the if-else statements with the code above, set debugging to true, and tell me what is printed in the output.

It says “target not found,” and then “target found.” then it continues to say “saw target.” So for some reason, my raycast keeps returning as nil even though there is clearly a part in the way.

The second argument in the :RayCast function should be a direction. For example, if you have a part located in 4,5,9 and you want to ray cast from that part to above the part, what you should not do is put part.Position+Vector3.new(0, 1, 0) as the second argument in the ray cast function, instead you should put Vector3.new(0, 1, 0) .

So in this case you should put object.Position-npc.Head.Position instead of object.Position

1 Like

I did what you said, and the NPC stopped thinking it could see the player through the wall. However, when it pathfinds around the wall, and then there is actually line of sight with the player, the function still returns as false.