0

我想解决的问题:

  1. 当我向右滑动屏幕时,立方体开始在 Y 轴上旋转,
  2. 当它达到 30° 时,立方体 y 旋转平滑地捕捉到 90°。平滑我的意思是快速动画到 90°,而不是突然改变它。但这是第二个问题,不是最重要的。 在此处输入图像描述

对于负值的左方向也是如此。

我尝试并徒劳地组合了很多代码,阅读了有关四元数和欧拉的信息,但无法找到合适的解决方案。我希望你们能帮助我了解统一的新知识。非常感谢。

4

1 回答 1

0

正如用户BIELIK此线程中所述,您可以使用以下代码通过滑动旋转对象:

#if UNITY_EDITOR
                float x = -Input.GetAxis("Mouse X");
#elif UNITY_ANDROID

                float x = -Input.touches[0].deltaPosition.x;
#endif
                transform.rotation *= Quaternion.AngleAxis(x * speedRotation, Vector3.up);

(当然,你需要附加这个属于你要旋转的GameObject的组件)

请注意,第一个if条件用于简化 Unity 编辑器上的测试,因此您无需在每次测试时都将应用程序构建到您的设备中(如果您正在为手机构建应用程序)。

关于捕捉功能,您可以使用一些基本逻辑:

//call this function from your update method
//snappedAngle is the angle where snapping is fixed (in your drawing, would be 0)
//snapThresholdAngle is the angle you decide to apply the snapping once surpassed (in your case, 30)

CheckSwipeProgress(snappedAngle, snapThresholdAngle) {
    float currentAngle = transform.eulerAngles;
    if (currentAngle > snappedAngle + snapThresholdAngle) {
        snappedAngle = (snappedAngle > 265) ? snappedAngle = 0 : snappedAngle += 90;
    }
    //in this case we need to implicitly check the negative rotation for the snapped angle 0, since eulerAngles have range [0,360]
    else if (currentAngle < snappedAngle - snapThresholdAngle || ((snappedAngle == 0) && currentAngle < 360 - snapThresholdAngle && currentAngle > 270)) {
        snappedAngle = (snappedAngle < 5) ? snappedAngle = 270 : snappedAngle -= 90;
    }
    transform.eulerAngles.y = snappedAngle;
    //if you implement interpolation, it would substitute the line right above this one.
}

请注意,对于三元条件,我尝试找到奇异情况(270 度或 0 度),但我比较的是稍低/更大的数字。它只是为了确保数值精度(避免 ==),并且不会对您的应用程序产生任何行为影响,因为snappedAngle只能是 0、90、180 和 270。

另请注意,您可以根据需要分别用localRotationlocalEulerAngles替换旋转eulerAngles 。

最后,关于插值,有很多线程解释了如何执行它。检查这个。唯一要考虑的是奇异情况,因为如果您从 310 插值到 0(例如),运动将遵循相反的方向。您需要在 310 和 360 之间进行插值,然后将偏航值分配为 0。

于 2020-10-04T11:28:33.357 回答