- Home /
Enemy AI don't collide with objects or rotate.
I found this script on Unity Answers and it seemed to work for the poster, but when I added it into my game, it resulted in the enemy AI from every part of the scene converging to attack the player even though they should be waiting until the player comes within a certain distance. They all have character controllers, but they still go through all objects and "stick" to the player's collider when they get too close. The script also seems to have code for the enemies to turn to face the direction they are moving, but they just slide sideways.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
//max distance from target before attack
public int maxDistance;
private Transform myTransform;
void Awake() {
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 2;
}
// Update is called once per frame
void Update () {
//Draws Targeting Line for Debugging
Debug.DrawLine(target.position, myTransform.position, Color.green);
//NPC Look atTarget
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
//NPC will move is its distance from target is greater then the max distance. Sets NPC range
if(Vector3.Distance(target.position, myTransform.position) > maxDistance){
//NPC Move Towards Targeting
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
Any ideas as to how to fix this would be much appreciated, I am doing this for a school project and the deadline is approaching quickly.
Your answer
Follow this Question
Related Questions
Precise hitboxes for characters 1 Answer
AI Script attached to Enemy and is Rotating around player 0 Answers
Player pushback when collide with enemy 2 Answers
Rotating on X and Z axis only 2 Answers
Enemy collision with wall, destroys wall 2 Answers