【发布时间】:2016-05-18 16:02:14
【问题描述】:
我对 unity 还很陌生,我以一种特殊的方式使用它来创建非游戏 2D 应用程序所以我只使用 UI 元素。我有一些我想做的事情的问题。我有一个跟随手指(或鼠标)旋转的对象,但该对象不能离开“区域” 这是我现在的代码:
using UnityEngine;
using System.Collections;
public class SteeringWheel : MonoBehaviour
{
public float angleMax = 90.0f;
private float baseAngle = 0.0f;
void OnMouseDown()
{
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
pos = Input.mousePosition - pos;
baseAngle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg;
baseAngle -= Mathf.Atan2(transform.right.y, transform.right.x) * Mathf.Rad2Deg;
}
void OnMouseDrag()
{
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
pos = Input.mousePosition - pos;
float ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - baseAngle;
Debug.Log("ang1 : " + ang);
ang = Mathf.Clamp(ang, -90, 90);
if (transform.eulerAngles.z >= 89 && transform.eulerAngles.z <= 271)
{
transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y, 0.7f, transform.rotation.w);
return;
}
transform.rotation = Quaternion.AngleAxis(ang, Vector3.forward);
}
}
这是问题的 GIF:
【问题讨论】:
-
您不小心使用了“四元数”。不要出于任何原因在 Unity 中使用“四元数”。只需设置微不足道的 eulerAngles。或者,更简单,只需使用“Rotate”(“RotateAround”也很方便。)Cordialement,
-
四元数对于进行 3D 旋转非常有用,因此使用它们没有任何问题。至于旋转问题,我真的不明白为什么要创建一个具有固定 Z 值的新四元数。你永远不应该用你自己的 X、Y、Z 和 W 值创建你自己的四元数,除非你知道如何正确使用它们,因为它们不是欧拉值。尝试像你已经做的那样用 Angleaxis 交换它,但是用 transform.rotation.eulerangles 代替
-
@PatrickDahlin 我这样做是因为如果我不这样做,当我的光标超过 90°(在左侧)时,“滑块”会以 270° 的角度进入右侧
标签: unity3d rotation quaternions clamp