1
\$\begingroup\$

I wanted to know if there is a method on which I can rotate an object with an angle given (a float to be precise), I use trigonometry to calculate the angle between the two objects in a (x, z) plane perspective (using y as the height coordinates).

enter image description here

This is the code I use to calculate the angle, but I want to know if a float would be anough data (then pass a Vector3 with that angle calculation as the Y parameter, since I want to rotate the Y axis).

//Makes the player heads to the direction the ball is...
public float headOnBall()
{
    Vector3 playerPos = this.transform.position;
    Vector3 ballPos = ball.transform.position;

    float angle;
    float x = (playerPos.x - ballPos.x);
    float z = (playerPos.z - ballPos.z);

    if(playerPos.z < ballPos.z || playerPos.x < ballPos.x && playerPos.z < ballPos.z)
    {
        angle = (Mathf.Atan2(z, x) + (Mathf.PI * 2)) * Mathf.Rad2Deg;
    }
    else
    {
        angle = Mathf.Atan2(z, x) * Mathf.Rad2Deg;
    }

    return angle;
}

Thanks in advance.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

There's a few functions for this already in Unity 3D:

\$\endgroup\$
1
  • \$\begingroup\$ I also tried converting mi float to Euler angles, then gave that as parameter for Quaternion Lerp and it seems to work, but I'll try those functions to see which suits better. Thanks! \$\endgroup\$ Commented Oct 1, 2016 at 2:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .