球のワールド座標をInverseTransformPointでキューブを基準とした座標系に変換してやればよさそうですね。
C#
1using UnityEngine;
2
3public class WorldAndLocalAtan2 : MonoBehaviour
4{
5 [SerializeField] private GameObject sphere;
6
7 private void Start()
8 {
9 // ベクトルがワールド座標系を基準としていれば...
10 var worldDt = this.sphere.transform.position - this.transform.position;
11 Debug.Log($"Cube world position : {this.transform.position.ToString("G")}");
12 Debug.Log($"Sphere world position : {this.sphere.transform.position.ToString("G")}");
13
14 // 得られる角度もワールド座標の軸を基準にしたものになるでしょう
15 Debug.Log($"World Atan2 : {Mathf.Atan2(worldDt.z, worldDt.x)}");
16
17 // 両オブジェクトのワールド座標をキューブのローカル座標系での座標に直すと...
18 var cubeLocalPosition = this.transform.InverseTransformPoint(this.transform.position);
19 var sphereLocalPosition = this.transform.InverseTransformPoint(this.sphere.transform.position);
20 var localDt = sphereLocalPosition - cubeLocalPosition;
21 Debug.Log($"Cube local position : {cubeLocalPosition.ToString("G")}");
22 Debug.Log($"Sphere local position : {sphereLocalPosition.ToString("G")}");
23
24 // 得られる角度はキューブの軸を基準にしたものになるでしょう
25 Debug.Log($"Local Atan2 : {Mathf.Atan2(localDt.z, localDt.x)}");
26
27 // なお、cubeLocalPositionはキューブローカル座標の原点であり、常に(0, 0, 0)になるはずです
28 // そのため、わざわざ2つの座標の差を求めずとも、sphereLocalPositionがそのまま
29 // キューブに対する球の相対的位置を表しているので、下記でもいいでしょう
30 Debug.Log($"Local Atan2 : {Mathf.Atan2(sphereLocalPosition.z, sphereLocalPosition.x)}");
31 }
32}
計算誤差によりsphereLocalPosition.z
に小さな値が入ってしまい、Atan2がぴったり0にはなりませんでしたが、おおむね0になりました。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/02/23 04:26
2019/02/23 10:18
退会済みユーザー
2019/02/23 17:09