2017-08-23 4 views
0

質問があります。私は画面上に4つのオブジェクトを持ち、下の写真のように発射物を持っています。 image sourceGameObject transform.Rotate()

4つの発射物のオブジェクトをクリックすると、クリックしたオブジェクトの位置が変わります。 これは使用されるコードですが、動作しません。

public GameObject Tun; 
public GameObject[] robotColliders; 
public GameObject[] Robots; 

foreach(GameObject coll in robotColliders) 
    { 
     coll.GetOrAddComponent<MouseEventSystem>().MouseEvent += SetGeometricFigure; 
    } 

    private void SetGeometricFigure(GameObject target, MouseEventType type) 
{ 
    if(type == MouseEventType.CLICK) 
    { 
     Debug.Log("Clicked"); 
     int targetIndex = System.Array.IndexOf(robotColliders, target); 
     Tun.transform.DORotate(Robots[targetIndex].transform.position, 2f, RotateMode.FastBeyond360).SetEase(Ease.Linear); 
    } 
} 

私はコンポーネントDORotate()を使用することを考えていましたが、とにかく動作しません。誰もがこの問題を解決する方法を知っていますか?

答えて

1

1つの方法は、四角形を使用して、オブジェクトと矢印の間のベクトルを使用して角度を取得することです。

Vector2 dir = Robots[targetIndex].transform.position - Tun.transform.position; 
Tun.transform.rotation = Quaternion.Euler(0, 0, Mathf.atan2(dir.y, dir.x)*Mathf.Rad2Deg - 90); // may not need to offset by 90 degrees here; 
+0

ああ、確かに、それは完璧にありがとうございます))) – George

0

このような単純な作業では、多くの可動部分があります。ユニティマニュアルは(https://docs.unity3d.com/ScriptReference/Mathf.Atan2.htmlを参照)、物事のこの種を行うには、正しい(最も効率的)な方法である例があります。

using UnityEngine; 
using System.Collections; 

public class ExampleClass : MonoBehaviour { 
    public Transform target; 
    void Update() { 
     Vector3 relative = transform.InverseTransformPoint(target.position); 
     float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg; 
     transform.Rotate(0, angle, 0); 
    } 
} 

これは、Y軸を中心にオブジェクトを回転させて操作する(ATAN2は、XとZを占め理由です):異なる軸が必要な場合は、それらを変更してコードを適応させます。

+0

nice .......))))))))) – George

関連する問題