GameObject transform.Rotate()

时间:2017-08-23 13:48:30

标签: c# unity3d rotation dotween

我有一个问题。我在屏幕上有4个物体和一个如下图所示的抛射物。 image source

当我点击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(),但它无论如何都不起作用。有谁知道如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

一种方法是使用四元数来设置围绕z轴的旋转,使用对象和箭头之间的向量来获得角度。

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;

答案 1 :(得分:0)

对于这么简单的任务来说,这是很多活动部分。 Unity手册有一个示例,它是执行此类操作的正确(最有效)方式(请参阅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的原因):如果您需要不同的轴,只需通过更改它们来调整代码。

相关问题