Monday, April 4, 2011

How To Rotate A Cube In 3D With Matrix

How To Rotate A Cube In 3D With Matrix:

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

[...]

No comments:

Post a Comment