Archive

Archive for January, 2009

Method of removing all event listeners

January 26th, 2009

So over the weekend I was talking to a buddy of mine in regards to different ways of removing event listeners from objects. The way that I usually do it is that everything that requires a listener is placed in a “addListeners” method and and its counter part is placed in a “removeListeners” method. That’s a very simple way of doing it. It works all the time as long as you are on top of every single object that requires having a listener added and you place it on both functions.

Don’t get me wrong, that work around works pretty good but becomes sort of a drag at times (eh, call me lazy) so I came up with a more automated way of doing it! A little disclaimer though, the method that I am about to describe works in 99.9% of my cases because all my classes extend an abstract class of some sort. Anyway, let me show you how I go about it:

What I do is archive all the added listeners and then remove them later in a loop. Everything is done at the abstract class level

private var arrListeners:Array = [];

I then override the “addEventListener” method in order to push references into the array as so:

override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
{
        super.addEventListener(type, listener, useCapture, priority, useWeakReference);
        arrListeners.push({type:type, listener:listener});
}

Now that you have a way to reference the added listeners, you would loop through the array to remove the listeners which still exist when needed:

private function clearEvents():void
{
   for(var i:Number = 0; i<arrListeners.length; i++){
      if(this.hasEventListener(arrListeners[i].type){
         this.removeEventListener(arrListeners[i].type, arrListeners[i].listener);
      }
   }
   arrListeners = null
}

That’s basically it. After that, if the object does not extend a class with that method, then I would just use the first method mentioned above.

You can download a quick example here. If you guys have any other ways of doing it, or can enhance the way that I am doing it now, please do let me know. Hope this helps!

Lab, as3

Newest JigLibFlash Team Member!

January 22nd, 2009

http://www.jiglibflash.com/blog/

http://www.jiglibflash.com/blog/

I am very very honored to join the development team of what may become the one of the best, if not, THE BEST 3D physics engine for flash!

My role is still not 100% defined but I will most probably be working on syntax and integration with the various 3D engines. Although I do have a few ideas up my sleeve which I will share with you once approved a solidified ;) . Keep in mind that the ported engine is still in it’s very early days and I have to make sure that I’m on the same page with the other members before I start working my way through it.

Very exciting times are ahead, now I need to figure out how to add more hours to a day. LOL

One more thing, I will still continue to enhance the FirstPersonCamera3D class (which is currently being converted into an API considering the fact that it will support “plug in” classes). So keep a lookout for that as well in the near future!

Lab

FirstPersonCamera3D updated to v1.9

January 21st, 2009

First of all, I just want to say thanks for all the feedback I got from you guys. So, THANKS!

A few MAJOR changes have been made to the FirstPersonCamera3D class:

Change made to initialize method

In order for the class to work, the initialize method now accepts the viewport instance as it’s first argument instead of a reference to the stage (the other two arguments are explained in the next paragraph).

firstPersonCamera.initialize(viewport, .2, .2);

Movement logic revamped

The entire code for the actual moving around has been totally revamped, hence, removing its dependency to Tweener or any other tween engine for that matter. Also, all ENTER_FRAMES have been removed and movement is calculated in the “look” method. With the new logic, moving in diagonal directions is way smoother also.

Along with the revamp came two new properties which will greatly increase the way we use movement: “speed” and “friction“. By adding these properties, we can simulate various types of movement, anywhere from gliding on ice to trying to move in quicksand!

Speed could be a number 0 – 1 where 0 is full stop and 1 is really really fast. Defaults to .2

Friction is a number 0 – 1 where 1 does not allow you to move and 0 is really really slippery. Defaults to .1

These properties can be directly set in the “initialize” method as so:

firstPersonCamera.initialize(viewport, .2, .2);

… where the second argument is “speed” and the third argument is “friction”

Change in the “mapKeys” method

The “mapKeys” methods can now accept any of the following:

FirstPersonCamera3D.ARROWS;  //maps only the arrow keys
FirstPersonCamera3D.WASD;  //maps the wasd keys
FirstPersonCamera3D.WASD_AND_ARROWS;  //maps both arrows and wasd keys

New moveBounds property

Another newly added property is “moveBounds”. This property limits the cameras movement to a set of predetermined boundries. Essentially, its like placing the camera within 4 walls. This is the syntax:

firstPersonCamera.moveBounds = {front:3500, back:-3500, left:-3500, right:3500};

For several hours I tinkered around with the class trying to set up collision detection, but then I figured that the best way to deal with collisions is to actually have some sort of “plugin” system where you could essentially integrate the FirstPersonCamera3D object with your Physics Engine of choice! This may be coming sooner than you think ;)

Here’s the new class:

package
{
    import flash.display.Stage;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.utils.*;
   
    import org.papervision3d.cameras.Camera3D;
    import org.papervision3d.core.math.Number3D;
    import org.papervision3d.view.Viewport3D;
   
    /**
     * Camera3D object with First Person functionality
     * @author Reynaldo Columna
     *
     */

    public class FirstPersonCamera3D extends Camera3D
    {
       
        /**
         * Holds the key codes for the arrow keys
         */

        public static const ARROWS:Object = {left:37, right:39, forward:38, back:40};
        /**
         * Holds the key codes for the "w", "a", "s" and "d" keys
         */
       
        public static const WASD:Object = {left:65, right:68, forward:87, back:83};
        /**
         *  Holds the key codes for both the "w", "a", "s" and "d" keys and the arrow keys
         */
       
        public static var WASD_AND_ARROWS:Array;
       
        protected static const UP_ARROW:int = 38;
        protected static const LEFT_ARROW:int = 37;
        protected static const RIGHT_ARROW:int = 39;
        protected static const DOWN_ARROW:int = 40;
       
        private static var FORWARD_KEY:int;
        private static var LEFT_KEY:int;
        private static var RIGHT_KEY:int;
        private static var BACK_KEY:int;
       
        protected var _sensitivity:Number;
        protected var _maxRotationX:Number;
        protected var _maxRotationY:Number;
        protected var _stageReference:Stage;
        protected var _viewportReference:Viewport3D;
        protected var _friction:Number;
        protected var _speed:Number;
        protected var _mode:String;
        protected var _moveBounds:Object;
       
        private var mouseDownPositionX:Number;
        private var mouseDownPositionY:Number;
        private var currentRotationY:Number;
        private var currentRotationX:Number;
       
        private var velocity:Number3D;
        private var movingForward:Boolean;
        private var movingLeft:Boolean;
        private var movingRight:Boolean;
        private var movingBack:Boolean;
        private var doManualLook:Boolean;
        private var useBothSetsOfKeys:Boolean;
       
        /**
         * Constructs the camera just as you would with a Camera3D object
         * @param fov
         * @param near
         * @param far
         * @param useCulling
         * @param useProjection
         *
         */
 
        public function FirstPersonCamera3D(fov:Number=60, near:Number=10, far:Number=5000, useCulling:Boolean=false, useProjection:Boolean=false)
        {
            super(fov, near, far, useCulling, useProjection);
        }
       
        /**
         * initializes the camera functionality
         * @param $viewport viewport
         * @param $speed 0 - 1 where 0 is full stop and 1 is really really fast! Defaults to .2
         * @param $friction 0 - 1 where 1 does not allow you to move and 0 is really really slippery! Defaults to .1
         *
         */
       
        public function initialize($viewport:Viewport3D, $speed:Number = 0.2, $friction:Number = 0.1):void
        {
            viewportReference = $viewport;
            stageReference = viewportReference.containerSprite.stage;
            friction = map($friction, 0, 1, 1, 0);
            speed = map($speed, 0, 1, 0, 100);
            movingForward = false;
            movingLeft = false;
            movingRight = false;
            movingBack = false;
            moveBounds = null;
            velocity = new Number3D();
            useBothSetsOfKeys = false;
            FirstPersonCamera3D.WASD_AND_ARROWS = [FirstPersonCamera3D.ARROWS, FirstPersonCamera3D.WASD];
            addListeners();
        }
       
        /**
         * Maps the keys to be used for movement. If no keys are specified, the arrow keys are used as defauilt.
         * @param keys An object with the following values: forward, back, left and right. Each should be a key code.
         *
         */
 
        public function mapKeys(keys:* = null):void
        {
            if(keys == FirstPersonCamera3D.WASD_AND_ARROWS){
                useBothSetsOfKeys = true;
                keys = null
            }
            FirstPersonCamera3D.FORWARD_KEY = ((keys != null) ? keys.forward : FirstPersonCamera3D.UP_ARROW) || FirstPersonCamera3D.UP_ARROW;
            FirstPersonCamera3D.BACK_KEY = ((keys != null) ? keys.back : FirstPersonCamera3D.DOWN_ARROW) || FirstPersonCamera3D.DOWN_ARROW;
            FirstPersonCamera3D.LEFT_KEY = ((keys != null) ? keys.left : FirstPersonCamera3D.LEFT_ARROW) || FirstPersonCamera3D.LEFT_ARROW;
            FirstPersonCamera3D.RIGHT_KEY = ((keys != null) ? keys.right : FirstPersonCamera3D.RIGHT_ARROW) || FirstPersonCamera3D.RIGHT_ARROW;
        }
       
        /**
         * Unregisters mapped keys
         *
         */
 
        public function removeKeyMapping():void
        {
           FirstPersonCamera3D.FORWARD_KEY = FirstPersonCamera3D.BACK_KEY = FirstPersonCamera3D.LEFT_KEY = FirstPersonCamera3D.RIGHT_KEY = -1;
        }
       
        /**
         * Makes the camera "look" around based on the mouse position
         * @param $sensitivity Number 0 to 1 representing how sensible the camera is to the mouse movement.
         * @param $maxRotationX Number representing the max horizontal rotation (0 to 360)
         * @param $maxRotationY Number representing the max vertical rotation (0 to 360)
         *
         */
 
        public function look($sensitivity:Number = 0.5, $maxRotationX:Number = 90, $maxRotationY:Number = 90):void
        {
            sensitivity = $sensitivity;
            maxRotationX = $maxRotationX;
            maxRotationY = $maxRotationY;
           
            if(mode == "auto"){
                var horizontalDegrees:Number = map(stageReference.mouseX, 0, stageReference.stageWidth, maxRotationX * -1, maxRotationX);
                var verticalDegrees:Number = map(stageReference.mouseY, 0, stageReference.stageHeight, maxRotationY * -1, maxRotationY);
                rotationX += (verticalDegrees - rotationX) * sensitivity;
                rotationY += (horizontalDegrees - rotationY) * sensitivity;
            }else if(mode == "manual"){
                if(doManualLook){
                    var horizontalDistance:Number = stageReference.mouseX - mouseDownPositionX;
                    var verticalDistance:Number = stageReference.mouseY - mouseDownPositionY;
                    var finalRotationX:Number = currentRotationX + (verticalDistance * (sensitivity * .5));
                    var finalRotationY:Number = currentRotationY + (horizontalDistance * (sensitivity * .5));
                    rotationX += (finalRotationX - rotationX) * sensitivity;
                    rotationY += (finalRotationY - rotationY) * sensitivity;
                }
            }
           
            renderMovement();
        }
       
        private function addListeners():void
        {
            stageReference.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
            stageReference.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
        }
       
        private function removeListeners():void
        {
            stageReference.removeEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
            stageReference.removeEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
            stageReference.removeEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
            stageReference.removeEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
        }
       
        private function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number
        {
            return min2 + (max2 - min2) * (value - min1) / (max1 - min1);
        }
       
        private function renderMovement():void
        {
            if(movingBack){
                velocity.z -= speed * Math.cos(rotationY * (Math.PI / 180));
                velocity.x -= speed * Math.sin(rotationY * (Math.PI / 180));
            }
           
            if(movingForward){
                velocity.z += speed * Math.cos(rotationY * (Math.PI / 180));
                velocity.x += speed * Math.sin(rotationY * (Math.PI / 180));
            }
           
            if(movingLeft){
                velocity.z += speed * Math.sin(rotationY * (Math.PI / 180));
                velocity.x -= speed * Math.cos(rotationY * (Math.PI / 180));
            }
           
            if(movingRight){
                velocity.z -= speed * Math.sin(rotationY * (Math.PI / 180));
                velocity.x += speed * Math.cos(rotationY * (Math.PI / 180));
            }
 
            velocity.multiplyEq(friction);
 
            x += velocity.x;
            z += velocity.z;
           
            if(moveBounds != null){
                if(x < moveBounds.left) x = moveBounds.left;
                if(x > moveBounds.right) x = moveBounds.right;
                if(z < moveBounds.back) z = moveBounds.back;
                if(z > moveBounds.front) z = moveBounds.front;
            }
           
        }
       
        public function clear():void
        {
            removeListeners();
            stageReference = null;
            viewportReference = null;
        }
       
        /*
        Properties
        */

       
        /**
         * Sets or returns the look sensitivity
         * @return Number
         *
         */
 
        public function get sensitivity():Number { return _sensitivity }
        public function set sensitivity(value:Number):void { _sensitivity = value; }

        /**
         * Sets or returns the maximum horizontal rotation
         * @return Number
         *
         */
 
        public function get maxRotationX():Number { return _maxRotationX }
        public function set maxRotationX(value:Number):void { _maxRotationX = value; }
       
        /**
         * Sets or returns the maximum vertical rotation
         * @return Number
         *
         */

        public function get maxRotationY():Number { return _maxRotationY }
        public function set maxRotationY(value:Number):void { _maxRotationY = value; }
       
        /**
         * Sets or returns a reference to the stage
         * @return Number
         *
         */
 
        public function get stageReference():Stage { return _stageReference }
        public function set stageReference(value:Stage):void { _stageReference = value; }
       
        /**
         * Sets or returns a reference to the viewport
         * @return
         *
         */
       
        public function get viewportReference():Viewport3D { return _viewportReference }
        public function set viewportReference(value:Viewport3D):void { _viewportReference = value; }
       
        /**
         * Sets or returns the friction
         * @return
         *
         */
       
        public function get friction():Number { return _friction }
        public function set friction(value:Number):void { _friction = value; }
       
        /**
         * Returns or set the speed of movement
         * @return
         *
         */
       
        public function get speed():Number { return _speed }
        public function set speed(value:Number):void { _speed = value; }
       
        /**
         * Sets or returns the camera mode. The mode can be either auto or manual. Setting the mode to
         * auto will make the camera look around automatically based on the mouse movement. Setting it
         * to manual will make the camera look around only when you click and drag.
         * @return
         *
         */
 
        public function get mode():String
        {
            return _mode
        }
        public function set mode(value:String):void
        {
            _mode = value;
            switch(_mode.toLowerCase())
            {
                case "manual" :
                stageReference.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
                stageReference.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
                break
               
                case "auto" :
                stageReference.removeEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
                stageReference.removeEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
                break
            }
        }
       
        /**
         * Sets or gets an object whith values that contraing the camera movement with bounds. The values are
         * "left", "right", "back" and "front"
         * @return
         *
         */
       
        public function get moveBounds():Object { return _moveBounds; }
        public function set moveBounds( value:Object ) { _moveBounds = value; }
       
        /*
        Handlers
        */

       
        private function handleKeyDown(evt:KeyboardEvent):void
        {
            switch(evt.keyCode)
            {
                case FirstPersonCamera3D.FORWARD_KEY:
                movingForward = true;
                break;
               
                case FirstPersonCamera3D.BACK_KEY:
                movingBack = true;
                break;
               
                case FirstPersonCamera3D.LEFT_KEY:
                movingLeft = true;
                break;
               
                case FirstPersonCamera3D.RIGHT_KEY:
                movingRight = true;
                break;
            }
            if(useBothSetsOfKeys){
                switch(evt.keyCode)
                {
                    case FirstPersonCamera3D.WASD.forward:
                    movingForward = true;
                    break;
                   
                    case FirstPersonCamera3D.WASD.back:
                    movingBack = true;
                    break;
                   
                    case FirstPersonCamera3D.WASD.left:
                    movingLeft = true;
                    break;
                   
                    case FirstPersonCamera3D.WASD.right:
                    movingRight = true;
                    break;
                }
            }
        }
       
        private function handleKeyUp(evt:KeyboardEvent):void
        {
            switch(evt.keyCode)
            {
                case FirstPersonCamera3D.FORWARD_KEY:
                movingForward = false;
                break;
               
                case FirstPersonCamera3D.BACK_KEY:
                movingBack = false;
                break;
               
                case FirstPersonCamera3D.LEFT_KEY:
                movingLeft = false;
                break;
               
                case FirstPersonCamera3D.RIGHT_KEY:
                movingRight = false;
                break;
            }
            if(useBothSetsOfKeys){
                switch(evt.keyCode)
                {
                    case FirstPersonCamera3D.WASD.forward:
                    movingForward = false;
                    break;
                   
                    case FirstPersonCamera3D.WASD.back:
                    movingBack = false;
                    break;
                   
                    case FirstPersonCamera3D.WASD.left:
                    movingLeft = false;
                    break;
                   
                    case FirstPersonCamera3D.WASD.right:
                    movingRight = false;
                    break;
                }
            }
        }
       
        private function handleMouseDown($event:MouseEvent):void
        {
            mouseDownPositionX = stageReference.mouseX;
            mouseDownPositionY = stageReference.mouseY;
            currentRotationY = rotationY;
            currentRotationX = rotationX;
            doManualLook = true;
        }
       
        private function handleMouseUp($event:MouseEvent):void
        {
            doManualLook = false;
        }
       
    }
}

[EDIT]

General setup :

firstPersonCamera = new FirstPersonCamera3D();
firstPersonCamera.initialize(viewport, .2, .2);
firstPersonCamera.y = 750;
firstPersonCamera.focus = 11;
firstPersonCamera.mode = "manual";
firstPersonCamera.moveBounds = {front:3500, back:-3500, left:-3500, right:3500};
firstPersonCamera.mapKeys(FirstPersonCamera3D.WASD_AND_ARROWS);
.
.
.
override protected function onRenderTick(event:Event=null):void
{
    firstPersonCamera.look(0.5);
    renderer.renderScene(scene, firstPersonCamera, viewport);
}

Experiment, Lab, papervision3d

FirstPersonCamera3D updated to v1.5

January 18th, 2009

Hi All:


[EDIT : CLICK HERE FIND THE LATEST VERSION]

I’ve made a few changes to the FirstPersonCamera3D class I first introduced in this post. The class now has two extra properties:

myCamera.removeMappedKeys()

and

myCamera.mode

myCamera.mode sets or returns the camera mode. The mode can be either auto or manual. Setting the mode to auto will make the camera look around automatically based on the mouse movement. Setting it to manual will make the camera look around only when you click and drag.

myCamera.removeMappedKeys() unregisters the keys used for movement using the mapKeys method. Remember, if no keys are specified, the arrow keys are used as default.

Here’s a sample setup:

firstPersonCamera = new FirstPersonCamera3D();
firstPersonCamera.initialize(stage);
firstPersonCamera.mode = "manual"
firstPersonCamera.y = 750;
firstPersonCamera.mapKeys();

Here’s the new class:

package
{
    import caurina.transitions.Tweener;
   
    import flash.display.Stage;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.utils.*;
   
    import org.papervision3d.cameras.Camera3D;
   
    /**
     * Camera3D object with First Person functionality
     * @author Reynaldo Columna
     *
     */

    public class FirstPersonCamera3D extends Camera3D
    {
        protected static const UP_ARROW:int = 38;
        protected static const LEFT_ARROW:int = 37;
        protected static const RIGHT_ARROW:int = 39;
        protected static const DOWN_ARROW:int = 40;
       
        private static var FORWARD_KEY:int;
        private static var LEFT_KEY:int;
        private static var RIGHT_KEY:int;
        private static var BACK_KEY:int;
       
        protected var _sensitivity:Number;
        protected var _maxRotationX:Number;
        protected var _maxRotationY:Number;
        protected var _stageReference:Stage;
        protected var _moveIncrement:Number;
        protected var _mode:String;
       
        private var forwardTrigger:uint;
        private var leftTrigger:uint;
        private var rightTrigger:uint;
        private var backTrigger:uint;
        private var intervals:Array;
        private var mouseDownPositionX:Number;
        private var mouseDownPositionY:Number;
        private var currentRotationY:Number;
        private var currentRotationX:Number;
       
        private var movingForward:Boolean;
        private var movingLeft:Boolean;
        private var movingRight:Boolean;
        private var movingBack:Boolean;
        private var doManualLook:Boolean;
       
        /**
         * Constructs the camera just as you would with a Camera3D object
         * @param fov
         * @param near
         * @param far
         * @param useCulling
         * @param useProjection
         *
         */
   
        public function FirstPersonCamera3D(fov:Number=60, near:Number=10, far:Number=5000, useCulling:Boolean=false, useProjection:Boolean=false)
        {
            super(fov, near, far, useCulling, useProjection);
            intervals = [forwardTrigger, leftTrigger, rightTrigger, backTrigger];
            movingForward = false;
            movingLeft = false;
            movingRight = false;
            movingBack = false;
        }
       
        /**
         * Initializes the Camera functionality
         * @param $stage A reference to the stage in order to add the key listeners
         * @param $moveIncrement A number which represents the move increment
         *
         */
   
        public function initialize($stage:Stage, $moveIncrement:Number = 250):void
        {
            stageReference = $stage;
            moveIncrement = $moveIncrement;
            addListeners();
        }
       
        /**
         * Maps the keys to be used for movement. If no keys are specified, the arrow keys are used as defauilt.
         * @param $keys An object with the following values: forward, back, left and right. Each should be a key code.
         *
         */
   
        public function mapKeys($keys:Object = null):void
        {
            FirstPersonCamera3D.FORWARD_KEY = (($keys != null) ? $keys.forward : FirstPersonCamera3D.UP_ARROW) || FirstPersonCamera3D.UP_ARROW;
            FirstPersonCamera3D.BACK_KEY = (($keys != null) ? $keys.back : FirstPersonCamera3D.DOWN_ARROW) || FirstPersonCamera3D.DOWN_ARROW;
            FirstPersonCamera3D.LEFT_KEY = (($keys != null) ? $keys.left : FirstPersonCamera3D.LEFT_ARROW) || FirstPersonCamera3D.LEFT_ARROW;
            FirstPersonCamera3D.RIGHT_KEY = (($keys != null) ? $keys.right : FirstPersonCamera3D.RIGHT_ARROW) || FirstPersonCamera3D.RIGHT_ARROW;
        }
       
        /**
         * Unregisters mapped keys
         *
         */
   
        public function removeKeyMapping():void
        {
            clearInterval(leftTrigger);
            clearInterval(rightTrigger);
            clearInterval(backTrigger);
            clearInterval(backTrigger);
            FirstPersonCamera3D.FORWARD_KEY = FirstPersonCamera3D.BACK_KEY = FirstPersonCamera3D.LEFT_KEY = FirstPersonCamera3D.RIGHT_KEY = -1;
        }
       
        /**
         * Makes the camera "look" around based on the mouse position
         * @param $sensitivity Number 0 to 1 representing how sensible the camera is to the mouse movement.
         * @param $maxRotationX Number representing the max horizontal rotation (0 to 360)
         * @param $maxRotationY Number representing the max vertical rotation (0 to 360)
         *
         */
   
        public function look($sensitivity:Number = 0.5, $maxRotationX:Number = 90, $maxRotationY:Number = 90):void
        {
            sensitivity = $sensitivity;
            maxRotationX = $maxRotationX;
            maxRotationY = $maxRotationY;
           
            if(mode == "auto"){
                var horizontalDegrees:Number = map(stageReference.mouseX, 0, stageReference.stageWidth, maxRotationX * -1, maxRotationX);
                var verticalDegrees:Number = map(stageReference.mouseY, 0, stageReference.stageHeight, maxRotationY * -1, maxRotationY);
                rotationX += (verticalDegrees - rotationX) * sensitivity;
                rotationY += (horizontalDegrees - rotationY) * sensitivity;
            }else if(mode == "manual"){
                if(doManualLook){
                    var horizontalDistance:Number = stageReference.mouseX - mouseDownPositionX;
                    var verticalDistance:Number = stageReference.mouseY - mouseDownPositionY;
                    var finalRotationX:Number = currentRotationX + (verticalDistance * (sensitivity * .5));
                    var finalRotationY:Number = currentRotationY + (horizontalDistance * (sensitivity * .5));
                    rotationX += (finalRotationX - rotationX) * sensitivity;
                    rotationY += (finalRotationY - rotationY) * sensitivity;
                }
            }
        }
       
        /**
         * Clears the camera
         *
         */
   
        public function clear():void
        {
            removeListeners();
            for(var a:Number = 0; a<intervals.length; a++){
                if(intervals[a] != undefined){
                    clearInterval(intervals[a]);
                    intervals[a] = null;
                }
            }
            intervals = null;
            stageReference = null;
        }
       
        private function addListeners():void
        {
            stageReference.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
            stageReference.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
        }
       
        private function removeListeners():void
        {
            stageReference.removeEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
            stageReference.removeEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
        }
       
        private function move($direction:String, $distance:Number):void
        {
            var distanceZ:Number
            var distanceX:Number
           
            switch ($direction) {          
                case "FORWARD" :
                distanceZ = $distance * Math.cos(rotationY*(Math.PI/180));
                distanceX = $distance * Math.sin(rotationY*(Math.PI/180));
                Tweener.addTween(this, {z:z+distanceZ, x:x+distanceX, time:0.5, transition:"linear"});
                break;
               
                case "REVERSE" :
                distanceZ = $distance * Math.cos(rotationY*(Math.PI/180));
                distanceX = $distance * Math.sin(rotationY*(Math.PI/180));
                Tweener.addTween(this, {z:z-distanceZ, x:x-distanceX, time:0.5, transition:"linear"});
                break;
               
                case "STRAFELEFT" :
                distanceZ = $distance * Math.sin(rotationY*(Math.PI/180));
                distanceX = $distance * Math.cos(rotationY*(Math.PI/180));
                Tweener.addTween(this, {z:z+distanceZ, x:x-distanceX, time:0.5, transition:"linear"});
                break;
               
                case "STRAFERIGHT" :
                distanceZ = $distance * Math.sin(rotationY*(Math.PI/180));
                distanceX = $distance * Math.cos(rotationY*(Math.PI/180));
                Tweener.addTween(this, {z:z-distanceZ, x:x+distanceX, time:0.5, transition:"linear"});
                break;
            }          
        }
       
        private function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number
        {
            return min2 + (max2 - min2) * (value - min1) / (max1 - min1);
        }
       
        /*
        Properties
        */

       
        /**
         * Sets or returns the look sensitivity
         * @return Number
         *
         */
   
        public function get sensitivity():Number { return _sensitivity }
        public function set sensitivity(value:Number):void { _sensitivity = value; }

        /**
         * Sets or returns the maximum horizontal rotation
         * @return Number
         *
         */
   
        public function get maxRotationX():Number { return _maxRotationX }
        public function set maxRotationX(value:Number):void { _maxRotationX = value; }
       
        /**
         * Sets or returns the maximum vertical rotation
         * @return Number
         *
         */

        public function get maxRotationY():Number { return _maxRotationY }
        public function set maxRotationY(value:Number):void { _maxRotationY = value; }
       
        /**
         * Sets or returns a reference to the stage
         * @return Number
         *
         */
   
        public function get stageReference():Stage { return _stageReference }
        public function set stageReference(value:Stage):void { _stageReference = value; }
       
        /**
         * Sets or returns the movement increment
         * @return Number
         *
         */
   
        public function get moveIncrement():Number { return _moveIncrement }
        public function set moveIncrement(value:Number):void { _moveIncrement = value; }
       
        /**
         * Sets or returns the camera mode. The mode can be either auto or manual. Setting the mode to
         * auto will make the camera look around automatically based on the mouse movement. Setting it
         * to manual will make the camera look around only when you click and drag.
         * @return
         *
         */
   
        public function get mode():String
        {
            return _mode
        }
        public function set mode(value:String):void
        {
            _mode = value;
            switch(_mode.toLowerCase())
            {
                case "manual" :
                stageReference.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
                stageReference.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
                break
               
                case "auto" :
                stageReference.removeEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
                stageReference.removeEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
                break
            }
        }
       
        /*
        Handlers
        */

       
        private function handleKeyDown(evt:KeyboardEvent):void
        {
            switch(evt.keyCode)
            {
                case FirstPersonCamera3D.FORWARD_KEY:
                if(!movingForward){
                    forwardTrigger = setInterval(move, 100, "FORWARD", moveIncrement);
                    movingForward = true;
                }
               
                break;
               
                case FirstPersonCamera3D.BACK_KEY:
                if(!movingBack){
                    backTrigger = setInterval(move, 100, "REVERSE", moveIncrement);
                    movingBack = true;
                }
               
                break;
               
                case FirstPersonCamera3D.LEFT_KEY:
                if(!movingLeft){
                    leftTrigger = setInterval(move, 100, "STRAFELEFT", moveIncrement);
                    movingLeft = true;
                }
               
                break;
               
                case FirstPersonCamera3D.RIGHT_KEY:
                if(!movingRight){
                    rightTrigger = setInterval(move, 100, "STRAFERIGHT", moveIncrement);
                    movingRight = true;
                }
               
                break;
            }
        }
       
        private function handleKeyUp(evt:KeyboardEvent):void
        {
            switch(evt.keyCode)
            {
                case FirstPersonCamera3D.FORWARD_KEY:
                clearInterval(forwardTrigger);
                movingForward = false;
                break;
               
                case FirstPersonCamera3D.BACK_KEY:
                clearInterval(backTrigger);
                movingBack = false;
                break;
               
                case FirstPersonCamera3D.LEFT_KEY:
                clearInterval(leftTrigger);
                movingLeft = false;
                break;
               
                case FirstPersonCamera3D.RIGHT_KEY:
                clearInterval(rightTrigger);
                movingRight = false;
                break;
            }
        }
       
        private function handleMouseDown($event:MouseEvent):void
        {
            mouseDownPositionX = stageReference.mouseX;
            mouseDownPositionY = stageReference.mouseY;
            currentRotationY = rotationY;
            currentRotationX = rotationX;
            doManualLook = true;
        }
       
        private function handleMouseUp($event:MouseEvent):void
        {
            doManualLook = false;
        }
       
    }
}

Lab

Papervision3D : Creating a custom mesh

January 13th, 2009

Hi:

A while back, a friend of mine was working on a project in which he needed to have several trapezoid like objects floating in space which he would then later manipulate their positions to form a larger shape. We figured that the best way to go about it was to create our own trapezoid primitive in papervision using the available core classes. Needless to say, the project deadline was too close to even try it out so we ended up using trapezoid like movieclips as materials. Of course using a natively drawn mesh would have done wonders to the processor but I guess it is what is its. The thought of creating my own custom primitive (or better said, custom mesh) in papervision still lingered though. Finally, I got time to dig in and give it a shot and the results are not to shabby if I do say so myself!

Start of by creating an instance of the Trianglemesh3D class and some variables we will need in a bit:

var mesh:TriangleMesh3D = new TriangleMesh3D();
var width:Number = 500;
var height:Number = 500;
var difference:Number = .25

A mesh is basically 2 or more triangles used to form a shape. Each triangle in turn is made up of 3 vertices. The trapezoid class we’ll be examining will only use two triangles to create the shape. The first thing we need to do is plot out the vertices. A trapezoid has four corners hence we need 4 vertices:

var tl:Vertex3D = new Vertex3D(-width*0.5, height*0.5, 0); // top left
var tr:Vertex3D = new Vertex3D(width*0.5, height*0.5, 0); // top right
var br:Vertex3D = new Vertex3D(width*0.5 - (width * difference), -height*0.5, 0); // bottom right
var bl:Vertex3D = new Vertex3D(-width*0.5 + (width * difference), -height*0.5, 0); // bottom left

In the code above, “width” and “height” are self explanatory, “difference” is a number (0 – .5) indicating the length of the shorter side of the trapezoid in relation to the longest side.

Don’t forget to add the vertices to the geometry of our mesh:

mesh.geometry.vertices.push(tl, tr, bl, br);

Now that we have our vertices plotted, we need to “connect the dots” to create our triangles. In order to create our triangles we need to use the Triangle3D class which accepts as arguments the mesh which will hold the triangle, an array of vertices to draw the triangle on, a material, and an array containing 3 NumberUV objects which I will explain later in this post.

Let’s set up our vertex arrays, one for each triangle:

var triangle_1_vertices:Array = [bl, tl, tr];
var triangle_2_vertices:Array = [br, bl, tr];

Now let’s set up our corresponding NumberUV arrays. Again, one for each triangle:

var textureMap_1:Array = [new NumberUV(0, 0), new NumberUV(0, 1), new NumberUV(1, 1)];
var textureMap_2:Array = [new NumberUV(1, 0), new NumberUV(0, 0), new NumberUV(1, 1)];;

The UVs basically tell the Triangle3D instance how to map the texture. (0, 0) would be bottom-left, (0, 1) is top-left, top-right is (1, 1) and bottom-right is (1, 0).

Let’s quickly throw together the material we will be using for our mesh:

var material:ColorMaterial = new ColorMaterial(0x00CC00);
var wireMaterial:WireframeMaterial = new WireframeMaterial(0x000000);
var composite:CompositeMaterial = new CompositeMaterial();
composite.addMaterial(material);
composite.addMaterial(wireMaterial);

Now to set up our triangles:

var triangle_1_face:Triangle3D = new Triangle3D(mesh, triangle_1_vertices, composite, textureMap_1);
var triangle_2_face:Triangle3D = new Triangle3D(mesh, triangle_2_vertices, composite, textureMap_2);

Now we add our triangles (or faces) to the geometry of our mesh and finally tell the mesh that its geometry is set to be rendered:

mesh.geometry.faces.push(triangle_1_face, triangle_2_face);
mesh.geometry.ready = true;

We’re done! You can now add your mesh to the 3d scene and manipulate as you would any DisplayObject3D!

Here is the Trapezoid class I made using the code we just used above:

package
{
   import org.papervision3d.core.geom.TriangleMesh3D;
   import org.papervision3d.core.geom.renderables.Triangle3D;
   import org.papervision3d.core.geom.renderables.Vertex3D;
   import org.papervision3d.core.math.NumberUV;
   import org.papervision3d.core.proto.MaterialObject3D;

   public class Trapezoid extends TriangleMesh3D
   {
     
      private var height:Number;
      private var width:Number;
      private var difference:Number;
     
      public function Trapezoid($material:MaterialObject3D = null, $width:Number = 500, $height:Number = 500, $difference:Number = 0.5)
      {
         super($material, new Array(), new Array());
         width = $width;
         height = $height;
         difference = $difference * 0.5;
         buildTrapazoid();
      }
     
      private function buildTrapazoid():void
      {
         var materialInstance:MaterialObject3D = material;
         var arrVertices:Array = geometry.vertices;
         var arrFaces:Array = geometry.faces;
         
         // create vertices
         var tl:Vertex3D = new Vertex3D(-width*0.5, height*0.5, 0); // top left
         var tr:Vertex3D = new Vertex3D(width*0.5, height*0.5, 0); // top right
         var br:Vertex3D = new Vertex3D(width*0.5 - (width * difference), -height*0.5, 0); // bottom right
         var bl:Vertex3D = new Vertex3D(-width*0.5 + (width * difference), -height*0.5, 0); // bottom left
         
         //add vertices
         arrVertices.push(tl, tr, bl, br);
         
         // create faces
         var triangle_1_vertices:Array = [bl, tl, tr];
         var triangle_2_vertices:Array = [br, bl, tr];
         
         var textureMap_1:Array = [new NumberUV(0, 0), new NumberUV(0, 1), new NumberUV(1, 1)];
         var textureMap_2:Array = [new NumberUV(1, 0), new NumberUV(0, 0), new NumberUV(1, 1)];
         
         var triangle_1_face:Triangle3D = new Triangle3D(this, triangle_1_vertices, materialInstance, textureMap_1);
         var triangle_2_face:Triangle3D = new Triangle3D(this, triangle_2_vertices, materialInstance, textureMap_2);
           
         // add faces      
         arrFaces.push(triangle_1_face, triangle_2_face);
         
         geometry.ready = true;
      }
     
   }
}

And here is a document class which shows you how to use it:

package
{
   import flash.events.Event;
   
   import org.papervision3d.materials.*;
   import org.papervision3d.materials.special.CompositeMaterial;
   import org.papervision3d.view.BasicView;

   public class CustomMesh extends BasicView
   {
      private var trapazoid:Trapazoid;

      public function CustomMesh()
      {
         camera.focus = 11;
         camera.zoom = 100;
         
         var material:ColorMaterial = new ColorMaterial(0x00CC00);
         var wireMaterial:WireframeMaterial = new WireframeMaterial(0x000000);
         var composite:CompositeMaterial = new CompositeMaterial();
         composite.addMaterial(material);
         composite.addMaterial(wireMaterial);
         
         composite.doubleSided = true;
         
         /*var movieMat:MovieAssetMaterial = new MovieAssetMaterial("Badge", true);
         movieMat.doubleSided = true;*/


         trapazoid = new Trapazoid(composite, 181, 246, .5);

         scene.addChild(trapazoid);
         startRendering();
      }

      override protected function onRenderTick(event:Event = null):void
      {
         trapazoid.yaw(2);
         super.onRenderTick(event);
      }
   }
}

These are the very basic first steps in creating your very own primitives in papervision. If you get build more complex, feature rich implementations please do let me know!!

Lab, papervision3d ,