0
\$\begingroup\$

I want to know when to use InverseTransformDirection. Unity documentation says : "Transforms a direction from world space to local space". Honestly, it is not clear for me.

I came across this piece of script for multilevel turret. "Barrels" is a child of "turretBase" and Barrels must face the target. I don't really undestand this script beacuse of InverseTransformDirection.

    private void RotateBarrelsToFaceTarget(Vector3 targetPosition)
    {
        Vector3 localTargetPos = turretBase.InverseTransformDirection(targetPosition - 
        barrels.position);
        Vector3 flattenedVecForBarrels = Vector3.ProjectOnPlane(localTargetPos, Vector3.up);
        ...
    }
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The InverseTransformDirection function is used to convert the target direction from world space to the local space. Which in your code the "turretBase" transform, enabling the correct calculation of the rotation needed for the "Barrels" to face the target within its local coordinate system.

Perhaps another way to understand this by trying out this code:

public class TestCode : MonoBehaviour
{
    public Transform playerTransform;

    private void Update()
    {
        // Get the input direction in world space
        Vector3 inputDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

        // Convert the input direction to local space of the player
        Vector3 localDirection = playerTransform.InverseTransformDirection(inputDirection);

        // Use the local direction for player movement
        // or
        Debug.Log(localDirection);
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ It's important not to confuse position with direction. \$\endgroup\$
    – Kevin
    Jun 22, 2023 at 20:08

You must log in to answer this question.

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