我有个问题。我在屏幕上有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(),但无论如何它都不起作用。有人知道如何解决这个问题吗?
发布于 2017-08-23 22:00:44
一种方法是使用四元数来设置围绕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;发布于 2017-08-23 22:11:02
对于这样一个简单的任务来说,这是大量的移动部件。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轴):如果您需要不同的轴,只需通过更改这些轴来调整代码。
https://stackoverflow.com/questions/45841591
复制相似问题