我目前有代码使用箭头键在表面上移动我的“播放器”,但我发现立方体摆动并且不能完美移动。因此,在几次运动后,坐标永远不会完美。总是喜欢90.0012或类似的东西,当我希望它是每个说90。有人有什么建议吗?这是代码:
using System.Collections;
using UnityEngine;
public class TumblingCubes : MonoBehaviour
{
public float tumblingDuration = 0.2f;
void Update()
{
var dir = Vector3.zero;
if (Input.GetKey(KeyCode.UpArrow))
dir = Vector3.forward;
if (Input.GetKey(KeyCode.DownArrow))
dir = Vector3.back;
if (Input.GetKey(KeyCode.LeftArrow))
dir = Vector3.left;
if (Input.GetKey(KeyCode.RightArrow))
dir = Vector3.right;
if (dir != Vector3.zero && !isTumbling)
{
StartCoroutine(Tumble(dir));
}
}
bool isTumbling = false;
IEnumerator Tumble(Vector3 direction)
{
isTumbling = true;
var rotAxis = Vector3.Cross(Vector3.up, direction);
var pivot = (transform.position + Vector3.down * 0.5f) + direction * 0.5f;
var startRotation = transform.rotation;
var endRotation = Quaternion.AngleAxis(90.0f, rotAxis) * startRotation;
var startPosition = transform.position;
var endPosition = transform.position + direction;
var rotSpeed = 90.0f / tumblingDuration;
var t = 0.0f;
while (t < tumblingDuration)
{
t += Time.deltaTime;
transform.RotateAround(pivot, rotAxis, rotSpeed * Time.deltaTime);
yield return null;
}
transform.rotation = endRotation;
transform.position = endPosition;
isTumbling = false;
}
}
答案 0 :(得分:0)
由于float
变量的精度问题,出现问题。谷歌关于浮动计算问题或类似的东西,你会明白这一点。在浮点数上进行多次乘法和除法通常会导致一些准确性缺陷,因为结果越来越近似。
要解决问题,请围绕endPosition
。有很多方法可以做到这一点,例如:
endPosition = new Vector3((int)endPosition.x, (int) endPosition.y, (int) endPosition.z);
或
endPosition.x = (int)endPosition.x;
endPosition.y = (int)endPosition.y;
endPosition.z = (int)endPosition.z;