This is probably the easiest way to simulate vision. We take a collider, be it a mesh or a Unity primitive, and use it as the tool for determining whether or not an object is inside the agent's vision range.
It's important to have a collider component attached to the same game object using the script on this recipe, as well as the other collider-based algorithms in this chapter. In this case, it's recommended that the collider is a pyramid-based one in order to simulate a vision cone. The fewer the polygons, the faster it will be in the game.
We will create a component that is able to see enemies nearby:
Visor
component declaring its member variables. It is important to add the following corresponding tags into Unity's configuration:using UnityEngine; using System.Collections; public class Visor : MonoBehaviour { public string tagWall = "Wall"; public string tagTarget = "Enemy"; public GameObject agent; }
void Start() { if (agent == null) agent = gameObject; }
public void OnTriggerStay(Collider coll) { // next steps here }
string tag = coll.gameObject.tag; if (!tag.Equals(tagTarget)) return;
GameObject target = coll.gameObject; Vector3 agentPos = agent.transform.position; Vector3 targetPos = target.transform.position; Vector3 direction = targetPos - agentPos;
float length = direction.magnitude; direction.Normalize(); Ray ray = new Ray(agentPos, direction);
RaycastHit[] hits; hits = Physics.RaycastAll(ray, length);
int i; for (i = 0; i < hits.Length; i++) { GameObject hitObj; hitObj = hits[i].collider.gameObject; tag = hitObj.tag; if (tag.Equals(tagWall)) return; } // TODO // target is visible // code your behaviour below
The collider component checks every frame if it is colliding with any game object in the scene. We leverage the optimizations to Unity's scene graph and engine, and focus only on how to handle the valid collisions.
After checking, if a target object is inside the vision range represented by the collider, we cast a ray in order to check whether it is really visible or if there is a wall in between.