问题描述
我要解决的问题:
- 当我向正确的方向滑动屏幕时,多维数据集开始 在Y轴上旋转
- 当达到30°时,立方体旋转 平稳捕捉到90°。顺便说一句,我的意思是快速动画到90°,而不是突然改变。但这是第二个问题,不是最重要的。
向左相同,但值为负。
我尝试并组合了很多代码,但徒劳无功,读到有关四元数和欧拉的信息,但找不到合适的解决方案。 我希望你们能对我的团结有所帮助,帮助我解决您的知识。 非常感谢。
解决方法
如this thread中用户 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。
请注意,您可以根据自己的需要,分别用 localRotation 和 localEulerAngles 替换 rotation 和 eulerAngles 需求。
最后,关于插值,有很多线程解释如何执行插值。 Check this one。唯一要考虑的是奇数情况,因为如果您从310插值到0(例如),则移动将遵循相反的方向。您需要在310和360之间进行插值,然后将偏航值分配为0。