1
votes

I've got a problem with my script, I want the enemy of mine, follow and rotate towards the player. while he's moving around. It seem to work nice, but when my player turning rotating 180 on y, my enemy seems to go back a lot(his position), and only when my player returning to his normal rotation , the enemy seem to come back. What did I do wrong?

public class EnemyTesting : MonoBehaviour
{

    public GameObject player;
   
    public float speed = 1.5f;
    public float turnRate;

    
    private void Update()
    {

        Vector3 toTarget = player.transform.position - transform.position;
        float angleToTarget = Vector3.Angle(transform.forward, toTarget);
        Vector3 turnAxis = Vector3.Cross(transform.forward, toTarget);

        transform.RotateAround(transform.position, turnAxis, Time.deltaTime * turnRate * angleToTarget);
        transform.Translate(toTarget * speed * Time.deltaTime);

    
    }
2

2 Answers

3
votes

By "goes back" I understand rotation, not position. I think that your problem is with Vector3.Angle. Check in the docs that the function returns the smaller of the two possible angles between the two vectors. In the case the angle is bigger than 180 you need to handle that in the code to make your enemy rotate accordingly.

Edit: I think that is produced by the rotation space of the translate function. Set Space.World in the transform.Translate arguments Try this:

private void Update() {
    Vector3 toTarget = player.transform.position - transform.position;
    transform.LookAt(player.transform.position);
    transform.Translate(toTarget * speed * Time.deltaTime, Space.World);
}

 
2
votes

You could use Quaternion.RotateTowards to slowly rotate the direction of the enemy towards the player.

This behavior also makes the enemy walk towards its forward vector, instead of directly at the player.

var towardsPlayer = player.transform.position - transform.position;

transform.rotation = Quaternion.RotateTowards(
    transform.rotation, 
    Quaternion.LookRotation(towardsPlayer), 
    Time.deltaTime * turnRate
);

transform.position += transform.forward * speed * Time.deltaTime;