Arczer
1
Hello,
I am trying to make my enemy AI only follow me once im within a certain distance from it and stop when im outside that distance.
Also when my enemy is following me it ignores all the walls and objects and just walks through them, how would I go about fixing this?
Here is my enemy AI code right now…
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int roataionSpeed;
public int maxDistance;
private Transform myTransform;
void Awake(){
myTransform = transform;
}
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 2;
}
void Update () {
Debug.DrawLine(target.position, myTransform.position, Color.yellow);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), roataionSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxDistance){
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
Thank you
Arczer
Your problem with distance detection is on this line:
if(Vector3.Distance(target.position, myTransform.position) > maxDistance){
It should be less than the distance:
if(Vector3.Distance(target.position, myTransform.position) < maxDistance){
As for walking through walls, the typical path is to add a Rigidbody component to the enemy (Component menu/Physics/Rigidbody). Then you will have to change the way you move your enemy. Change this line:
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
To something like:
rigidbody.AddForce(transform.forward * speed * Time.deltaTime);
Where ‘speed’ is a variable you define and set as appropriate. It may have to be larger depending on the mass you set for your object.
Note with physics, things tend to keep going so you may have to either change how you are applying force or add some sort of “drag” or “friction” to get what you want.
As an alternate solution, you can make your enemy AI a character controller rather than a Rigidbody. See CharacterController in the scripting reference.