AI Follow script

I’m using a simple script to make an AI enemy follow my players movements. However, I would also like the enemy ship to spin as it moves towards the player, but my current script stops the spinning. I was wondering how I can get around this? I would like the ship to rotate along the X axis whilst it moves towards the player along the Z axis. Here is the follow script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIFollow : 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));
        }

    }

}

And this is my rotating script:

public class Rotate : MonoBehaviour


{
    public Vector3 eulerAngleVelocity;
    public Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate()
    {
        Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime);
        rb.MoveRotation(rb.rotation * deltaRotation);
    }
}
1 Like

Bump

you need to look into lerp or lookrotation

right now line 23 is doing nothing because line 24 over writes it. line 23 says rotate me to look at the player, but then line 24 says new rotation = 0,90,0

and i would not have a rotate script. do both in the AIFollow script.

t += Time.deltaTime;     //  t is a float (starts at 0.0f)
if (t > 1.0f) t = 1.0f;       // when t reaches 1.0f your gameObject will be at the dest rotation
Quaternion start = transform.rotation;   // ai start rotation
Quaternion dest;     // some other rotation
transform.rotation = Quaternion.Lerp(start, dest, t);