How to make AI avoid walls etc ?
Right now , my enemy ai can detect my player with range variable and follow and shoot me ...... i want my ai to stop at certain distance and then shoot and also go back to its orignal position if the Player is not in the range. and last thing is that ai can move through walls too how to avoid that ? its my first question here so please help ! Here is my code :
using UnityEngine;
using System.Collections;
public class shootplayer : MonoBehaviour {
private Transform player;
public float attackDistance =10f;
//public float chase =10f;
public GameObject bullet;
public GameObject BulletHole;
public float delayTime = 8;
private float counter = 0 ;
public float enemyDamage=25f;
// Use this for initialization
void Start () {
player = GameObject.Find ("FPSController").GetComponent<Transform> ();
}
// Update is called once per frame
void Update () {
if (Vector3.Distance (transform.position, player.position) < chase){
transform.LookAt (player);
transform.position = Vector3.MoveTowards (transform.position, player.position, 5 * Time.deltaTime);
}
if (Vector3.Distance (transform.position, player.position) < attackDistance) {
Instantiate (bullet, transform.position, transform.rotation);
AudioSource audio = GetComponent <AudioSource> ();
audio.Play();
counter = 0;
RaycastHit hit;
Ray ray = new Ray (transform.position, transform.forward);
if (Physics.Raycast (ray, out hit, 100f))
if (hit.transform.tag == "Player") {
hit.transform.GetComponent <HealthScript> ().RemoveHealth(enemyDamage);
}
else
{
}
}
}
//void OnTriggerEnter(Collider other)
//{
//if (other.GetComponent<Collider>().name == "FPSController") {
//Destroy (gameObject);
//}
//}
}
Answer by Soraphis · Apr 22, 2016 at 05:11 PM
avoid enemy can walk through walls:
your enemy should be an physical object, with collision and all that stuff.
make ai avoid walls:
when your ai decides to walk to a certain position, it should calculate a path, it can walk along. you can use the unity navmesh for this (if it is possible for your game) or you could implement some kind of A*-Algorithm.
AI Behaviour:
To model your AI behaviour you can use some kind of behavour-tree or decision-tree. if you've a real complex ai, or multiple different ai's you should consider a graphical representation of those trees.