Let a enemy attack when he sees the player

Hey there,
Can someone help me

im using this code to try to let de enemy see
so he look if he can see the player or not.

But the problem is he can still see me whem im behind a wall
Can someone help me out ?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;

public class Test : MonoBehaviour
{
    [SerializeField]
    float distance;

    public GameObject player;
    public Transform Shootpoint;

    public bool CanSee = false;

    [SerializeField]
    float chaseDistence = 0.5f;



    void Update()
    {
        distance = Vector3.Distance(Shootpoint.position, player.transform.position);

        if (!Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
        {
            Debug.DrawLine(Shootpoint.position, player.transform.position, Color.red);
            CanSee = false;
            Debug.Log("CANT SEE");

        }
        else if (Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
        {
            Debug.DrawLine(Shootpoint.position, player.transform.position, Color.green);
            CanSee = true;
            Debug.Log("CAN SEE");
        }
    }
}

You’re smart to use Debug.DrawLine to see what’s going on. So the ray is going right through the wall? That should only be possible if the wall does not have a collider (or its collider is set to Trigger, or something like that).

i have do have a box collider around the wall yes but still it’s going right through

Physics.Raycast returns true if it hits any collider. You need to check what collider it hits to verify if it is the player or an obstacle. It is probably hitting the wall, returns true, and you are assuming true means it is hitting the player. Also, use just “else” instead of “else if” because the way you have it written you are doing the same raycast twice.

Relevant thread:

Scripting reference:

2 Likes

i want to do something similar to yours but i dont understand something
the raycast only is a line so how does he see you if you are not touching the raycast?
you could be in a diffrent angle than the raycast
(sorry i am new so if you can explain it to me i would really apreciate it)