PV3D_CubeRotation
Copyright (c) 2009 milkmidi
All rights reserved.
http://milkmidi.com
http://milkmidi.blogspot.com
/*
Copyright (c) 2009 milkmidi
All rights reserved.
http://milkmidi.com
http://milkmidi.blogspot.com
*/
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import org.papervision3d.cameras.CameraType;
import org.papervision3d.lights.PointLight3D;
import org.papervision3d.materials.shadematerials.PhongMaterial;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.view.BasicView;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.objects.primitives.Cube;
import org.papervision3d.events.InteractiveScene3DEvent;
[SWF(frameRate = "41", backgroundColor = "#111111", pageTitle = "milkmidi.com")]
public class PV3DCubeRotationDemo extends BasicView
{
private var rootNode :DisplayObject3D;
private var cube :Cube;
private var vx :Number = 0;
private var vy :Number = 0;
//速率
private var decay :Number = .98;
//衰竭值
private var mousePos :Point = new Point();
private var isMouseDown :Boolean = false;
public function PV3DCubeRotationDemo(){
super(0, 0, true,true,CameraType.TARGET);
camera.z = -950;
camera.focus = 12;
init3DObjects();
this.addEventListener(Event.ADDED_TO_STAGE , addToStageHandler);
}
private function addToStageHandler(e:Event):void {
startRendering();
stage.addEventListener(MouseEvent.MOUSE_DOWN, function (e:MouseEvent):void {
isMouseDown = true;
mousePos.x = stage.mouseX;
mousePos.y = stage.mouseY;
});
stage.addEventListener(MouseEvent.MOUSE_UP, function (e:MouseEvent):void {
isMouseDown = false;
});
}
private function init3DObjects():void {
rootNode = new DisplayObject3D();
scene.addChild(rootNode);
var _light :PointLight3D = new PointLight3D();
var _phongMat:PhongMaterial = new PhongMaterial(_light, 0xffffff, 0x999999, 10);
var _ml :MaterialsList = new MaterialsList( { all:_phongMat } );
cube = new Cube(_ml, 400, 400, 400);
rootNode.addChild(cube);
}
override protected function onRenderTick(e:Event = null):void {
if (isMouseDown == true) {
var _differenceX:int = mousePos.x - stage.mouseX;
var _differenceY:int = mousePos.y - stage.mouseY;
//算出上一個滑鼠座標和現在座標的距離差
cube.rotationY += _differenceX;
rootNode.rotationX += _differenceY;
mousePos.x = stage.mouseX;
mousePos.y = stage.mouseY;
vx = _differenceX / 10;
vy = _differenceY / 10;
}else {
/*
* 用上一個滑鼠座標的位置, 減去現在座標的位置
* 即可用來當作加速度,
* 加速度再乘上一個衰竭值,
* 即可讓加速度慢慢的漸近於0,
* 物件也就可以慢慢的靜止,
* 直到又賦予一個新的加速度。
* */
vx *= decay;
vy *= decay;
cube.rotationY += vx;
rootNode.rotationX += vy;
}
super.onRenderTick(e);
}
}
}