Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Issues with tumbling cube script

Discussion in 'Scripting' started by casiantumblr, Mar 20, 2018.

  1. casiantumblr

    casiantumblr

    Joined:
    Mar 20, 2018
    Posts:
    4
    Hi everyone, I'm trying to make a game, I need my cube to move on the play area tumbling so I found a nice script that at first look was working properly. The problem comes when the cube has to stop against a wall or another collider because it first gets stuck and then it is thrown away losing it's position.
    Can you help me solving that? Here's the code :

    using System.Collections;
    using UnityEngine;

    public class PlayerController : 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;
    }
    }


    I think it could be solved by using a rigidbody component and modifying a few lines but I'm not really confident with this kind of movement.