- Home /
[C#] Enemy flys at Player
So im having abit of problems with my EnemyAI script. The script works fine on a flat ground but if my player say, climbs a mountain, instead of the AI trying to follow him up the mountain, he just flys at him. I have tryed adding a Character Controller as well as a ridged body to the enemy to attempt to get it to stay on the ground. The character controller had no effect no matter what setting is applied to it, and the ridged body fixed the problem but created another one. It causes the enemyAI to glitch out and twitch when it reaches the maximum distance from the character where it normally would stop getting any closer. Code below, thanks in advance.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
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 = 3;
}
// Update is called once per frame
void Update () {
Debug.DrawLine (target.transform.position, myTransform.position, Color.yellow);
//Look at target
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if (Vector3.Distance (target.position, myTransform.position) > maxDistance) {
//Move at Targets
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
moving things with transform.position (line 40) will do that; please search UA/Google for hundreds of examples, tutorial/vids on simple AI
Your answer
![](https://koobas.hobune.stream/wayback/20220613143251im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Make AI walk around randomly until Player is Seen. (C#) 2 Answers
Camera rotation C# script problem 3 Answers
Simple enemy kill count 1 Answer
Distribute terrain in zones 3 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers