x


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?

more ▼

asked Apr 21 '10 at 09:25 AM

Mattivc gravatar image

Mattivc
1.7k 55 60 67

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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
        }

    }

}
more ▼

answered Apr 21 '10 at 09:29 AM

duck gravatar image

duck ♦♦
41.4k 95 152 415

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5275
x1581
x832
x672
x4

asked: Apr 21 '10 at 09:25 AM

Seen: 4135 times

Last Updated: Apr 21 '10 at 09:35 AM