1 de jun. de 2017

LookAt2D(Vector 3)

A method to rotate a Gameobject towards a Vector3 position.
In the example bellow, the Tank´s Canon is following the Mouse.





Put this code in the object that you want to rotate. Call the method inside the Update().

void LookAt2D(Vector3 target) // target is the Vector to look at
    {
        // Get point B based on point A as 0,0,0
        Vector3 targetDir = target - transform.position;

        // Use Tangent to get the Angle. 
        // Tan(x) = catetoOposto/catetoAdjacente
        float angleRad = Mathf.Atan2(targetDir.y, targetDir.x);
        // convert angle to Degrees
        float angleDeg = angleRad * Mathf.Rad2Deg;

        // I´ll rotate "angleDeg" in "Vector3.forward" Axis
        transform.rotation = Quaternion.AngleAxis(angleDeg, Vector3.forward);
    }

Nenhum comentário: