Search Unity

Rotate an object to target

Discussion in 'Scripting' started by angel_m, Feb 6, 2019.

  1. angel_m

    angel_m

    Joined:
    Nov 4, 2005
    Posts:
    1,160
    Hi, I'm using this known code to make the enemies follow the target (Player):

    void RotateToTarget() {
    Vector3 direction = target.position - transform.position;
    direction.y = 0;

    if (direction.magnitude < 0.1f)
    return;

    transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
    }


    The problem is my game scenary is spherical, it is a planet and when the player and the enemy are on the bottom part of the planet, the enemy turns upside down. On a normal plane scenery it works well.
    I have checked this behaviour is due the RotateToTarget method used, so I need to find another method to orient the enemy towards the target. (I'm afraid I am very bad in math..:()

    Any idea?
     
    Last edited: Feb 7, 2019
  2. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    Quaternion.LookRotation assumes that the up vector is Vector3.up (y+). You'll need to pass in your agent's up vector. I can't tell you exactly how to get that, since it depends on how your geometry is structured, but I suspect your up vector will generally be the agent's position - planet center.
     
  3. angel_m

    angel_m

    Joined:
    Nov 4, 2005
    Posts:
    1,160
    SOLVED: I had to add "transform.up" as the second parameter in LookRotation.
    Thanks.
     
    Last edited: Feb 10, 2019