How to roll a cube?

I want to roll a cube by 90 degrees whenever i press arrow keys in respective direction without attaching rigid-body to it. I want to roll the cube slowly(animation) by 90 degrees.
Help me with an example code.
Thanks in advance.

Your question is open to intrepretation. Here is a bit of code that rotates a cube on its edge to walk a cube through rotation.

#pragma strict

public var speed = 45.0;
private var offset = 0.5;  // Assues a cube of 1 unit on a side.
private var tr : Transform;
private var rotating = false;

function Start() {
	tr = transform;
}

function Update () {
	var pos : Vector3;
	
	if (Input.GetKeyDown(KeyCode.UpArrow) && !rotating) {
		pos = Vector3(tr.position.x, tr.position.y-offset, tr.position.z+offset);
		DoRotation(pos, Vector3.right, 90.0);	
	}
	else if (Input.GetKeyDown(KeyCode.DownArrow) && !rotating) {
		pos = Vector3(tr.position.x, tr.position.y-offset, tr.position.z-offset);
		DoRotation(pos, -Vector3.right, 90.0);	
	}
	else if (Input.GetKeyDown(KeyCode.RightArrow) && !rotating) {
		pos = Vector3(tr.position.x+offset, tr.position.y-offset, tr.position.z);
		DoRotation(pos, -Vector3.forward, 90.0);	
	}
	else if (Input.GetKeyDown(KeyCode.LeftArrow) && !rotating) {
		pos = Vector3(tr.position.x-offset, tr.position.y-offset, tr.position.z);
		DoRotation(pos, Vector3.forward, 90.0);	
	}
}

function DoRotation(pos : Vector3, axis : Vector3, degrees : float) {
	var curr = 0.0;
	rotating = true;
	while (curr != degrees) {
		curr = Mathf.MoveTowards(curr, degrees, Time.deltaTime * speed);
		tr.RotateAround(pos, axis, Time.deltaTime * speed);
		yield;
	}
	rotating = false;
}

Note this code does the rotation incrementally and it does not take into account the last fractional rotation. If you are going to be rotating a bunch of times, you will see errors in the rotation creep in, and therefore will have to add some additional code to assure the code has only it’s specified 90 degree rotation.

You can simply use a animation (with defined speed and rotation around center) and start the animation when key is pressed. This is sometimes the simplest solution. Or you can attach e.g. RotationCubeScript and in Update routine increase transform.EulerAngle.x/y/z until target angle or target increment is reached. Consider using more sophisticated functions such as Mathf.Lerp, Mathf.Dampf(angle). It should be simple code for a few lines.

Here’s a short Youtube video that covers exactly how to roll a cube on its edges: How to Move a Cube by Rolling it | Unity Tutorial - YouTube


rolling cube