Perfect rotation of a cube

时间:2018-04-18 17:44:37

标签: c# unity3d

I currently have a script to move my "Player" around a surface but I find it very uneffective, the cube wiggles left to right and up and down. Does anyone have any good scrips on how to move a cube, flipping side to side, without wiggling or whatever. that also moves perfectly each time? my last one would move to a point like 2.000231 or something like that. it was really fusterating because I'm trying to have it perfect so it would fit in an hole. He's the script I am using. If you have a better one pls include ty 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;

    }

}

1 个答案:

答案 0 :(得分:1)

您的脚本应该可以正常工作,因为浮点数的存储方式,您总是会遇到小错误。但你不应该有像你这样大的错误。

确定您的多维数据集是从(0,0,0)开始的吗? 无论如何,你可以肯定,如果你把它放在Tumble的末尾

    var vec = transform.eulerAngles;
    vec.x = Mathf.RoundToInt(vec.x / 90 * 90);
    vec.y = Mathf.RoundToInt(vec.y / 90 * 90);
    vec.z = Mathf.RoundToInt(vec.z / 90 * 90);
    transform.eulerAngles = vec;