- Home /
Unity AI/Enemy won't move towards target
Hello programmers around the world. I've been developing an AI for enemy and so far I have him wandering around. He can also detect the player but when that happens he should start moving towards him and he doesn't for some reason only his animation activates. Also when I get out of his fieldOfView or line of sight he returns to just wandering around. I only need to fix the moving towards the player issue.
Here is the code
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class EnemyScript : MonoBehaviour { [SerializeField] private EnemyScript enemy; private int randomNumber; [SerializeField] private Transform respawnPoint; [SerializeField] private float walkSpeed; [SerializeField] private float runSpeed; [SerializeField] private Animator eAnim; [SerializeField] private Transform player; // Use this for initialization void Start () { enemy.transform.GetChild(5).SetParent(null); } // Update is called once per frame void Update () { StartCoroutine(EnemyIdle(player)); FollowTarget (player); } private IEnumerator EnemyIdle(Transform player) { Transform target = respawnPoint.GetChild(randomNumber); Vector3 targetDir = target.position - transform.position; float step = walkSpeed * Time.deltaTime; Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F); transform.rotation = Quaternion.LookRotation(newDir); eAnim.SetBool("walk", true); transform.position = Vector3.MoveTowards(transform.position, target.position, walkSpeed * Time.deltaTime); if(Vector3.Distance(transform.position, target.position) < 0.01f) { eAnim.SetBool("walk", false); } yield return new WaitForSeconds(7); if (Vector3.Distance(transform.position, target.position) < 0.01f) { randomNumber = UnityEngine.Random.Range(0, respawnPoint.childCount); } } private void FollowTarget(Transform player){ float dist = Vector3.Distance(player.position, transform.position); if (dist < 10.0f){ StopAllCoroutines (); // get the target direction: Vector3 targetDir = player.position - transform.position; targetDir.y = 0; // kill any height difference to avoid tilting transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(targetDir), 3.0f * Time.deltaTime); if (dist > 2){ // check min distance // only move to the target if farther than min distance // THIS IS THE THAT DOESN"T WORK FOR SOME REASON??? transform.position += transform.forward * walkSpeed * Time.deltaTime; } } } }
If anybody has any tips I would greatly appreciate it.
Paste your code in, then highlight it and then click the '101' button.