How to detect certain object using raycast

Hi guys,

I have a problem which i can’t figure out. I want to do something like this:

If my camera’s raycast*(field of view)* hits a certain object*(enemy)* it will run an action*(for now just a debug.log)*. But it doesn’t ignore other objects. So if a wall stands in front of the enemy. The raycast doesn’t notice the enemy.

I have searched on google and UnityAnswers, and came up with masklayers.
But i didn’t knew how that worked.

var layerMask = 1 << 8;

I tried the reference code that they used:

    function Update () {

  // Bit shift the index of the layer (8) to get a bit mask

  var layerMask = 1 << 8;

  // This would cast rays only against colliders in layer 8.

  // But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.

  layerMask = ~layerMask;

  var hit : RaycastHit;

  // Does the ray intersect any objects excluding the player layer

  if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), hit, Mathf.Infinity, layerMask)) {

    Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) * hit.distance, Color.yellow);

    print ("Did Hit");

  } else {

    Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) *1000, Color.white);

    print ("Did not Hit");

  }

}

But again, i dont know how to set up a layer in the script.

Can anybody help me with this? Or knows a tutorial?

Thanks in advance!
Darryl Donohoe

There’s a much easier way to check visibility: use a Linecast from the character to the target, and check if the hit object is the target - if not, something is in between:

  var target: Transform; // the target transform
  ...
  private var hit: RaycastHit;
  if (Physics.Linecast(transform.position, target.position, hit) && hit.transform == target){
    // target is visible
  }

If you want to also check if the target is inside the viewing angle, use this:

var viewAngle: float = 120; // define the viewing angle

function CanSeeTarget(target: Transform): boolean {
  var hit: RaycastHit;
  return
    Vector3.Angle(transform.forward, target.position-transform.position) <= viewAngle 
    && Physics.Linecast(transform.position, target.position, hit) 
    && hit.transform == target
  ;
}

thank you, you’ve saved my life ^