Tom Krcha's FlashRealtime

Hey amigo!
I am Tom Krcha, Gaming Evangelist at Adobe. These are my notes


How To Rotate A Cube In 3D With Matrix

April 4th, 2011

Another simple trick to avoid locks when rotating objects in 3D.

Goal: rotate a cube in all axes and avoid axes to switch.

See the problem in a video:

1. Consider following scenario (WRONG):

Demo | Full source code

protected function init():void{
	box = new Box(200,200,200,2,2,2);
	box.setMaterialToAllFaces(new FillMaterial(0xFF0000,1,1));;
}
 
protected function onMouseMove(event:MouseEvent):void{
	if(!isDragging)
		return;
 
	var deltaX:int = lastX - event.stageX;
	var deltaY:int = lastY - event.stageY;
 
	lastX = event.stageX;
	lastY = event.stageY;
 
// IMPORTANT PART
	box.rotationZ += deltaX*Math.PI/180;
	box.rotationY += deltaY*Math.PI/180;
 
	camera.render();
}

When you use rotationZ and rotationY together you will find that by rotating the cube you switch axes and at the end you rotate different axes than you wanted at the beginning.

2. Solution: rotate with Matrix

Demo | Full source code

protected function init():void{
	box = new Box(200,200,200,2,2,2);
	box.setMaterialToAllFaces(new FillMaterial(0xFF0000,1,1));;
}
 
protected function onMouseMove(event:MouseEvent):void{
	if(!isDragging)
		return;
 
	var deltaX:int = lastX - event.stageX;
	var deltaY:int = lastY - event.stageY;
 
	lastX = event.stageX;
	lastY = event.stageY;
 
// IMPORTANT PART
	var matrix:Matrix3D = box.matrix;
 
	matrix.appendRotation(deltaX,new Vector3D(0,0,1));
	matrix.appendRotation(-deltaY,new Vector3D(1,0,0));
 
	box.matrix = matrix;
 
	camera.render();
}

See correct version - rotating a cube with:

Also if you have a different solution - don’t hesitate to share it. I am pretty sure, there are more ways to do this.