[solved] Linecast FOW problem

This issue has been somewhat tackled before, but I don’t seem to get my scenario to work.

I have three objects:

  • Hero (Rigidbody)
  • Wall (Box collider)
  • Enemy (Box collider)

Triangle (Mesh collider, Trigger, script)

Enemy has a triangle shaped child object (its field of view) and this child object has script attached to it that first checks for collisions and then linecasts if there’s anything in the way between Hero and Enemy.

It works at first but when hero starts moving the linecast will always return as false even if there was a wall between them.
Hero and Enemy are both in Ignore Raycast layer. What am I missing here?

Here’s the lineofsight code:

var hero : Transform; 
var enemy : Transform; 
private var hit : RaycastHit;

function OnTriggerStay(coll : Collider)
{
	if (coll.gameObject.name == "Hero" )
		testSight();
}

function testSight () 
{ 
   if (Physics.Linecast(hero.position, enemy.position, hit)) 
      print ("Sight obstructed by " + hit.collider.name); 
   else 
      print (enemy.name + " has a free line of sight to " + hero.name); 
}

and the scene for closer inspection

270098–9725–$ninja_744.zip (1.13 MB)

Are you sure the triangle-shaped object isn’t obstructing the linecast? A trigger doesn’t affect solid objects, but it does get hit by raycasts. You can switch this off using the Raycasts Hit Triggers option in the physics settings (menu Edit > Project Settings > Physics) or by putting the trigger on the Ignore Raycast layer.

1 Like

Tried both of them but without success, it still behaves oddly.

Well I did some checking and the linecast works perfectly when it’s in the FixedUpdate, regular Update brings the odd behaviour.
So after the collision how could I call the linecast function which would be inside the FixedUpdate?

You can do things like this by setting a boolean flag:-

var detected: boolean;

function OnTriggerStay(coll : Collider) 
{ 
   if (coll.gameObject.name == "Hero" ) 
      detected = true;
}

function FixedUpdate() {
    if (detected) {
        detected = false;

        if (Physics.Linecast(...) {
            ...
        }
    }
}

I had a similar problem to yours, and I found this tread on it, maybe it will help.
http://forum.unity3d.com/viewtopic.php?t=38957&highlight=moving+trigger

Thanks andeeee, that did the trick. But I noticed that when I put my computer in lot of stress and the game is pretty laggy the linecast still in some occasions sees through the wall.
But maybe it’s in acceptable limits. thanks again.