Search Unity

Ai rotation in spherical world

Discussion in 'Scripting' started by angel_m, May 28, 2020.

  1. angel_m

    angel_m

    Joined:
    Nov 4, 2005
    Posts:
    1,160
    I 'm using this simple code to rotate the ai enemy object towards the target (the player) in my spherical world project:

    void RotateTowards (Vector3 targetposition) {

    float rotsmooth=2.0f;

    Vector3 direction = targetposition - transform.position;

    transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction, transform.up), rotsmooth * Time.deltaTime);

    }

    It works ok when the player and the enemy are at the top of the sphere planet, just as if they were on a plane.

    The problem is when they are at the bottom of the sphere planet and the world coordinates are inverted, because then the enemy is not using the correct angles to rotate towards the target and the movement is odd.

    As you can see I 'm using transform.up in the transform.rotation instruction, in order to readjust the transform rotation correctly but it is not enough to achieve a correct behaviour.

    Any idea?