issue with raycast behavior

I am building a simple line of sight script in unity using javascript and on a flat plane it works just fine. However on terrain i get some issues mainly the object can’t seem to see the player. Is there an adjustment i can make for this?

right now this is the code i have for detecting the player:

function CanSeePlayer() : boolean
{
    var hit : RaycastHit;
    var rayDirection = Target.transform.position - transform.position; 

    // If the Target is close to this object and is in front of it, then return true
    if((Vector3.Angle(rayDirection, transform.forward)) < (fieldOfViewRange*2) && (Vector3.Distance(transform.position, Target.transform.position) <= attackRange))
    {
        inAttackRange = true;
        return true;
    }
    
	else
	{
		inAttackRange = false;
	}

    if((Vector3.Angle(rayDirection, transform.forward)) < fieldOfViewRange)
    { // Detect if player is within the field of view
        if (Physics.Raycast (transform.position, rayDirection, hit, SightRange)) 
        {
            if (hit.collider.gameObject == Target) 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

any help would be great.

thanks.

The ray is probably coming from your feet, which means it hits the ground if the ground has the smallest of bumps on it. To test, can add a Debug.DrawRay(transform.position,rayDrection);. You can only see it in scene mode, and it can be “off” from your real raycast, but it gives a hint.

Just pick a spot on the player where the “eyes” are, and a spot to look at on the enemy (if you use Target.position then you’re checking if you can see its feet, so small bumps can still block you):

var playerEyes : Vector3 = transform.poistion+Vector3.up*1.2;
var enemyChest : Vector3 = Target.position+Vector3.up*0.8;
rayDirection = enemyChest - playerEyes;

This is crude, but works for manlike things (I’m saying the eyes are always 1.2 meters up from the feet.) You could child an empty in front of the player’s head to be the eyes, and use: playerEyes=transform.Find("eyes").position;