【问题标题】:GameObject transform.Rotate()游戏对象变换。旋转()
【发布时间】:2017-08-23 13:48:29
【问题描述】:

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

【问题讨论】:

    标签: c# unity3d rotation dotween


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      对于这样一个简单的任务,有很多活动部件。 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):如果您需要不同的轴,只需通过更改这些来调整代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多