- Home /
How to see if a transform is visible without a camera
I am having trouble making an enemy script that will check whether the player is visible or obstructed from its point of view. If it is obstructed, the enemy will roam aimlessly. if it is visible, the enemy will move toward the player.
Answer by robertbu · Dec 31, 2013 at 03:11 AM
The typical (and simplistic) solution to this problem is to do a Physics.Raycast() from the enemy's position towards the player's position. If it hits, and if the hit.collider.name is 'Player', then you know the pivot point of the enemy can see the pivot point of the player. A more complete solution is to Raycast() from the position of the 'eyes' of the enemy to the corners of the mesh.bounds (transformed into world space) of the player. While also not perfect, it allow the enemy to see when only a small part of the player is visible.
var player: Transform;
function Update () {
var hit : RaycastHit;
if (!Physics.Raycast (transform.position, player.position - transform.position, hit) && hit.collider.name == "Player") {
Debug.Log("The enemy is seeing the player");
}
}
I don't know how far you want to take it, but you may also want to check the angle between the enemy forward and a vector between the enemy and the player. If it is above some threshold, then the enemy is facing away from the player.
Could you elaborate on how to get the position of mesh.bounds to raycast to?
Your answer
![](https://koobas.hobune.stream/wayback/20220613125210im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiate at hit.point 2 Answers
Arrow not shooting the in right orientation 0 Answers
Picking up rigidbody objects 2 Answers
Follow Nearest Target 1 Answer
Boolean being overwritten 1 Answer