So I have tried just about everything to find out how to script an AI following script correctly.
What my script is supposed to do: Always look at the Player.
What script does:
*When the Player is on the leftside of the Enemy my enemy looks left and vice versa.
*It moves up along it’s local y-as.
using UnityEngine;
using System.Collections;
public class AiZ : MonoBehaviour {
Transform target;
public float speed = .01f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
target = GameObject.FindWithTag ("Player").transform;
Vector3 forwardAxis = new Vector3 (0, 0, -1);
transform.LookAt (target.position, forwardAxis);
Debug.DrawLine (transform.position, target.position);
transform.eulerAngles = new Vector3 (0, 0, -transform.eulerAngles.z);
transform.position -= transform.TransformDirection (Vector2.up) * speed ;
}
}
using UnityEngine;
using System.Collections;
public class AiZ : MonoBehaviour {
public Transform target;//set target from inspector instead of looking in Update
public float speed = 3f;
void Start () {
}
void Update(){
//rotate to look at the player
transform.LookAt(target.position);
transform.Rotate(new Vector3(0,-90,0),Space.Self);//correcting the original rotation
//move towards the player
if (Vector3.Distance(transform.position,target.position)>1f){//move if distance from target is greater than 1
transform.Translate(new Vector3(speed* Time.deltaTime,0,0) );
}
}
}
public float speed = 0.5f;
public Transform Player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 displacement = Player.position -transform.position;
displacement = displacement.normalized;
if (Vector2.Distance (Player.position, transform.position) > 1.0f) {
transform.position += (displacement * speed * Time.deltaTime);
}else{
//do whatever the enemy has to do with the player
}
}