How to turn a cube to a face

Viewed 95

Regardless of the rotation of the cube, by pressing the button, the cube should rotate to the face.

Example:

enter image description here

My code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class CubeDoTweenController : MonoBehaviour
{
    private Quaternion targetRotation;


    private void Awake()
    {
        targetRotation = transform.rotation;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.D))
        {
            targetRotation *= Quaternion.FromToRotation(Vector3.up, Vector3.right);
            transform.DORotateQuaternion(targetRotation, 1f);
        }
        else if (Input.GetKeyDown(KeyCode.W))
        {
            targetRotation *= Quaternion.FromToRotation(Vector3.up, Vector3.forward);
            transform.DORotateQuaternion(targetRotation, 1f);
        }
    }
}

After a couple of turns, the old cube starts to rotate. Thanks in advance for any help

2 Answers

Ok I have the solution to your problem... Instead of using Vectro3 axis, try to use your transform axis like so:

transform.rotation *= Quaternion.FromToRotation(transform.up, transform.forward);

The thing is that what does Quaternion.FromToRotation(Vector3 from, Vector3 to) is calculating the angle between from and to. Then you apply this rotation on your transform which is local.

For exemple Quaternion.FromToRotation(Vector3.up, Vector3.right); generate a rotation of 90 degrees around z axis.

Applied two times on your game object, x axis equals -x axis

Quaternion.FromToRotation(Vector3.up, Vector3.forward); generate a rotation of 90 degrees around x axis.

But now, as your x axis equals -x axis, it is like the rotation around x has been inverted but if you follow the rotation of your cube, everything is fine.

Using local axis will then follow the rotation of your cube and do as your cube rotates in world space

Related