- Home /
How can I check the line of sight to see if the player is visible to the enemy?
How can I make an if statement that runs if there is a line of sight between two objects? For example checking if a enemy can see the player in a maze like map?
Answer by duck · Apr 21, 2010 at 09:29 AM
You can use Raycasting to do this.
Cast a ray from the enemy object to the player object, and check the hit results. If the first hit result is the player, then the enemy can see the player.
For example, in your Enemy script (make sure the "player" variable has a reference to the player in it):
var player : Transform;
function Update () {
var hit : RaycastHit;
var rayDirection = player.position - transform.position;
if (Physics.Raycast (transform.position, rayDirection, hit)) {
if (hit.transform == player) {
// enemy can see the player!
} else {
// there is something obstructing the view
}
}
}
Your answer
Follow this Question
Related Questions
Follow within a certain distance? 1 Answer
changing objects color through a raycast? 1 Answer
Player Die When Hit By Enemy 1 Answer
I want to click on my screen and make my character move there, having trouble with raycasts. 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers