Search Unity

LOS Checking

Discussion in 'Scripting' started by shaKu, May 21, 2009.

  1. shaKu

    shaKu

    Joined:
    May 19, 2009
    Posts:
    28
    I am a bit confused right now... all I am attempting to do is a simple LOS check from one object to another. I had the idea to simply do a Linecast from transform a to transform b but I thought this might cause a problem and collide with the collider for character a (since it is the nearest collider to the start of the line). I took a look at the FPS example on unity (with the Sentry Gun) which they use this same method. When I looked at the object using this script in the editor it appears that the object's transform is directly in the collider but the script still works... why would this be the case?

    Here is the code for the script I am using as a sample.

    Code (csharp):
    1.  
    2. var attackRange = 30.0;
    3. var shootAngleDistance = 10.0;
    4. var target : Transform;
    5.  
    6. function Start () {
    7.     if (target == null  GameObject.FindWithTag("Player"))
    8.         target = GameObject.FindWithTag("Player").transform;
    9. }
    10.  
    11. function Update () {
    12.     if (target == null)
    13.         return;
    14.    
    15.     if (!CanSeeTarget ())
    16.         return;
    17.    
    18.     // Rotate towards target   
    19.     var targetPoint = target.position;
    20.     var targetRotation = Quaternion.LookRotation (targetPoint - transform.position, Vector3.up);
    21.     transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0);
    22.  
    23.     // If we are almost rotated towards target - fire one clip of ammo
    24.     var forward = transform.TransformDirection(Vector3.forward);
    25.     var targetDir = target.position - transform.position;
    26.     if (Vector3.Angle(forward, targetDir) < shootAngleDistance)
    27.         SendMessage("Fire");
    28. }
    29.  
    30. function CanSeeTarget () : boolean
    31. {
    32.     if (Vector3.Distance(transform.position, target.position) > attackRange)
    33.         return false;
    34.        
    35.     var hit : RaycastHit;
    36.     if (Physics.Linecast (transform.position, target.position, hit))
    37.         return hit.transform == target;
    38.  
    39.     return false;
    40. }
    41.  
     
  2. HanulTech

    HanulTech

    Joined:
    Apr 5, 2009
    Posts:
    312
    Take a look at the Layers Mask parameter. You can use this to specify which objects should be ignored when doing your LOS check. Also, while I haven't checked this, I do not think the LOS will pick up the collider from the object from which it is cast, but if it does, then your solution is to say to ignore the unique layer containing the player.