Enemy following player problem.

Hey, my script for enemy following player works wrong. Ok, model is following me, but like this:

xDD.

I want to move it on the ground, not in air. xD

Script:

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 = 2;
		
	}
	
	// Update is called once per frame
	void Update () {
		Debug.DrawLine(target.position, myTransform.position, Color.yellow);
		
		//Patrzy na cel. 
	
		myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
	     
		if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
	    //Chodzi za celem.
		myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
	
	}
   }
}

Whats wrong? Thank’s for help, guys.

The LOCAL forward axis of your model is the global Y-. So when you say to your object to move forward towards the target, it points its local forward axis to the target, making the model lay down.

Two solutions:

-If you’re good at your modelling software (I’m not…), rotate the model to match the unity’s coordinate system and export it again.

-Put the model inside a null GameObject and apply the movimentation script into that null object. Adjust position and rotation so your model faces the local Z+ of the parent null object.

I’m making a simple game and all my objects hierarchy are organized in this fashion. A null game object is the parent with all behavior scrips. Inside that I have the mesh object (with the same coordinate system problem, so its rotated) and some secondary objects/meshes. It makes easy to keep the same logical object but replace the visual element.