- Home /
Simple AI Question
if (Physics.Raycast (ray, out hit)) { if (hit.collider.gameObject.tag == "Player") { Debug.Log ("Hit Player"); navmeshagent.SetDestination(player.position); }
I'm sure there's a simple answer to this, but I've been trying to code AI to follow the player when the Raycast emitted from the enemy hit the player. I can code for the enemy to move toward the destination of the player but there are two limitations of this code :
The enemy only ever moves toward the players initial destination and does not follow the player
Once the enemy reaches the players destination, enemy movement will only be initiated when the player walks back through the ray.
In short, I want to trigger enemy movement toward the player when the ray hits the player and the enemy to follow the player endlessly until destroyed.
Thanks!
Answer by Kishotta · Oct 08, 2017 at 06:31 PM
This code should either be running in
Update
, or (better) in a coroutine that executes every x (say, 0.1) seconds.You should make sure the ray is casting in the direction
player.position - transform.position
. This will make sure that the ray is blocked by obstacles in the same collision layer as the raycasts (by default, everything), essentially giving you line of sight. If you only update the navmesh target position when the player is detected, and do nothing when the player is not hit, your AI will always follow the last known position of the player.
If you just want the enemy to pursue the player regardless of line of sight and all that, then a raycast is completely unnecessary. Just set the navmesh destination to player.position
.
Thanks for this - I'm unsure as to how to code the coroutine? @$$anonymous$$ishotta
No problem.
To use a coroutine (which is good for performance in this case), use something similar to the following:
IEnumerator UpdateAINav (float navRefreshRate) {
while (player.isAlive) { // or while(true), just so long as we make sure the player exists
navmeshagent.SetDestination (player.position); // doing the simple version just because
yield return new WaitForSeconds (navRefreshRate);
}
}
Then in Start
or Awake
do:
void Awake () {
StartCoroutine (UpdateAINav (0.1f));
}