1 de jun de 2017

LookAt2D(Vector 3)

A method to rotate a Gameobject towards a Vector3 position.







void LookAt2D(Vector3 target)
    {
        // Get point B based on point A as 0,0,0
        Vector3 targetDir = target - canon.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
        canon.transform.rotation = Quaternion.AngleAxis(angleDeg, Vector3.forward);
    }

Nenhum comentário: