昨天发布的RubiksCube控制旋转部分的代码是操作根据物体自身的坐标,觉得还是有点怪,所以今天花了点时间改写了一下:实现了世界坐标的旋转。主要是解决了坐标系换算的问题,方法是用Quaternion生成旋转矩阵。代码贴出来,给有需要的朋友。
package {
import org.papervision3d.core.math.Quaternion;
import org.papervision3d.core.proto.LightObject3D;
import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.objects.primitives.Cube;
import org.papervision3d.view.BasicView;
import flash.events.*;
/**
* @author kevincao
*/
public class RotateControlDemo extends BasicView {
protected var cube : Cube;
private var isDown : Boolean = false;
private var _x : Number;
private var _y : Number;
private var _vx : Number = 0;
private var _vy : Number = 0;
public function RotateControlDemo() {
init();
}
protected function init() : void {
var light : LightObject3D = new LightObject3D();
light.x = 1000;
light.y = 1000;
light.z = -1000;
cube = new Cube(new MaterialsList({all : new FlatShadeMaterial(light)}), 300, 300, 300);
scene.addChild(cube);
addEventListener(Event.ENTER_FRAME, tick);
stage.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, upHandler);
}
private function downHandler(event : MouseEvent) : void {
_x = mouseX;
_y = mouseY;
isDown = true;
stage.addEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
}
private function upHandler(event : MouseEvent) : void {
isDown = false;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
}
private function moveHandler(event : MouseEvent) : void {
_vx = (mouseX - _x) * .4;
_vy = (mouseY - _y) * .4;
_x = mouseX;
_y = mouseY;
var q : Quaternion = Quaternion.createFromEuler(-_vx, 0, -_vy, true);
cube.transform.calculateMultiply3x3(q.matrix, cube.transform);
}
private function tick(event : Event) : void {
if(!isDown) {
if(_vx != 0 || _vy != 0) {
_vx *= .9;
_vy *= .9;
if(Math.abs(_vx) < .5) {
_vx = 0;
}
if(Math.abs(_vy) < .5) {
_vy = 0;
}
var q : Quaternion = Quaternion.createFromEuler(-_vx, 0, -_vy, true);
cube.transform.calculateMultiply3x3(q.matrix, cube.transform);
}
}
singleRender();
}
}
}