- Home /
Line Of Sight - should work, but doesn't
I'm working on simpliest line of sight mechanic for enemies. It consists of few elements: - In front of the enemy there is a Trigger Sphere. If player enters it, the trigger sends message to Enemy, that player is in range of sight. - Then, Enemy has a simple Raycast script to check, if there is something between him and Player. If there isn't, he starts chasing the player.
Simple as that. Everything works great through the Sphere Trigger, but Raycast doesn't. It just does nothing. No detection of player at all.
The Script for raycast detection:
function CheckLineOfSight(){
var hit : RaycastHit;
var rayDirection = Player.transform.position - transform.position;
Debug.Log("2");
if (Physics.Raycast (transform.position, rayDirection, hit)) {
if (hit.transform.tag == "Player") {
Debug.Log("3");
GETHIM();
}
}
}
Debug Log "2" works and shows up when Player enters Trigger Sphere. Debug Log "3" doesn't show at all. No errors too.
Researching google gave me no working answers.
Am I missing something?
Use linecast - http://docs.unity3d.com/ScriptReference/Physics.Linecast.html to see where your cast is going. I think rayDirection is not created right.
Sometimes issues occur if your ray cast starts inside a collider.
Try and remove that if statement after raycast and just log something when ray cast is successful.
if (Physics.Raycast (transform.position, rayDirection, hit)) {
Debug.Log("something");
}
This way you will be able to see whether your ray cast was successful or not. If it was, then there is some problem in your tag checking statement. I think it should be gameObject.tag ins$$anonymous$$d of transform.tag.
Answer by Vel_1828 · Jun 29, 2014 at 09:54 AM
AAAAH, works now! "Sometimes issues occur if your ray cast starts inside a collider." THAT was the issue. The Rayast was hitting the Trigger Sphere. I just set the trigger to layer "Ignore Raycast" and now it works perfectly. Thanks a lot to everyone! The Linecast will be most useful in the future too. :)
There is also an option buried somewhere (use google to find it) that makes the raycast automatically ignore all triggers.