transform.TransformPointでのユニティ座標変換



Unity Coordinate Transformation Transform



元のリンク
私がプロジェクトに取り組んでいたとき、要件がありました。 UIの操作オブジェクトでディスプレイスメントアニメーションを実行し、それを別の参照オブジェクトに移動する必要があります。 UI構造がより複雑であるため、操作オブジェクトと参照オブジェクトは異なる親オブジェクトの下の子オブジェクトであり、ローカル座標とワールド座標の変換が含まれます。 APIを確認したところ、Unityが対応するインターフェースであるTransform.TransformPointを提供していることがわかりました。相対座標の概念が明確にされていれば、非常に扱いやすいです。
画像
図に示すように、4つのゲームオブジェクト(キューブ)が作成されています。私の目標は、obj4の親オブジェクトを変更せずに、obj4をobj1とオーバーラップさせることです。 obj4はobj3の子であるため、インスペクターパネルに表示されるobj4の座標は、obj3のローカル座標を基準にしています。 obj4をobj1とオーバーラップさせたい場合は、ローカル座標の計算に限定され、目的の結果を得ることができません。

ワールド座標系に変換してからローカル座標系に変換し直すことにより、目的の結果を取得する必要があります。



obj1が目標であるため、移動するオブジェクトを基準にしたワールド座標は次のとおりです。
V1 =ターゲットobject.transform.TransformPoint(操作object.transform.localPosition)

ワールド座標が見つかりました。次に、相対ワールド座標を操作オブジェクトのローカル座標に変換します。
操作オブジェクト。 transform.InverseTransformPoint(v1)



結果は、obj4とobj1がオーバーラップするために必要なローカル座標になります。
テストを容易にするために、結論が正しいことを証明するために簡単なエディターが作成されました。
Unity transform.TransformPoint

最終的なテストコードは次のとおりです。

using UnityEngine using System.Collections using System.Collections.Generic public class InversePosition : MonoBehaviourpublic List<Transform> posList [HideInInspector] public Transform selectTransform [HideInInspector] public Transform targetTransform void Start()Print()public void Print()// The world coordinates of the operated obj Debug.Log(string.Format('World coordinates of the selected object ({00}]: {1}', selectTransform.name, selectTransform.transform.position)) // The local coordinates of the operated obj Debug.Log(string.Format('Local coordinates of the selected object ({00}]: {1}', selectTransform.name, selectTransform.transform.localPosition)) // World coordinates of the target obj Debug.Log(string.Format('The world coordinates of the target object ({0}}: {1}', targetTransform.name, targetTransform.transform.position)) // Local coordinates of the target obj Debug.Log(string.Format('Local coordinates of the target object ({0}): {1}', targetTransform.name, targetTransform.transform.localPosition)) // The world coordinates of the target obj relative to the operation obj (trabsform.TransformPoint) Vector3 v4 = targetTransform.transform.TransformPoint(selectTransform.localPosition) Debug.Log(string.Format('The world coordinates (TransformPoint) of the target obj relative to the selected obj: {00}', v4)) // The final position of the operation target Debug.Log(selectTransform.transform.InverseTransformPoint(v4)) } }

要約すると、目標位置を決定できる場合、特定のサブオブジェクトがその位置に移動されます。どちらも、tranform.TransformPointとtransform.InverseTransformPointの2段階の変換によって取得できます。