Nightwish Capone Mumford and Sons Get mp3 Cobra Starship Edge Of Sanity Bon Iver Dave Matthews Band Paramore Michael Buble Benabar She and Him MP3 search Michael Jackson

AdvancedED Flex 4 Book

AdvancED Flex 4 is now available to pre-order on Amazon.com. I had the privilege to work on this book with Elad Elrom and Shashank Tiwari. Once you get a copy please be sure to let us know what you think.

AdvancedED Flex 4 Book

Charlie Schulze

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to StumbleUpon Stumble This Post

The real reason for the iPhone 4 antenna issue

As suspected, gizmodo planted a bug.

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to StumbleUpon Stumble This Post

iTape 4

I couldn’t resist:

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to StumbleUpon Stumble This Post

Papervision Isometric View & Pathfinding with as3isolib and A* (A Star)

View Example

This week's example / tutorial is how to mix Papervision with as3isolib and A* (pronounced A Star) for a nice 3D isometric pathfinding experience. The version of A* that I am using comes straight out of Keith Peters book AdvancedEd ActionScript 3.0 Animation. Anyone looking to cover advanced animation topics in Flash should buy a copy of this book. It is excellent.

This tutorial will not cover how to create the A* classes but rather show you how to blend 3 things together; Papervision, as3isolib, and A* (the Keith Peters version). If you're just getting started using as3IsoLib take a look at these great tutorials and download the code: http://code.google.com/p/as3isolib/w/list

We will cover a few of the things that you need to successfully merge the pathfinding and 3D experience.

First item is our camera setting. We are setting ortho to true because this actually gives us a true isometric camera feel.

Actionscript:
  1. camera.ortho = true;

Inside of our makeGrid function we are setting up the groundwork for our pathfinding and isometric world. This grid has no information about the cellsize, just which parts of it are walkable and not walkable.

Actionscript:
  1. protected function makeGrid():void
  2. {
  3.     pathGrid = new Grid(10, 10);
  4.     for(var i:int = 0; i <20; i++)
  5.     {
  6.         pathGrid.setWalkable(Math.floor(Math.random() * 8) + 2,
  7.                           Math.floor(Math.random() * 8)+ 2,
  8.                           false);
  9.     }
  10.     drawGrid();
  11. }

Next we move on to drawGrid() which begins to connect the pathfinding and as3isolib

One of the great thing about as3isolib which is similar to papervision is that it has native objects that you can skin, such as boxes and polygons.

Here inside of drawGrid we run through the columns and rows that we setup in our makeGrid function. From the information in these loops we can get back the node information of the grid and check if an item is walkable or not walkable. If it is walkable we create a standard size box with a height of 0, if it is not walkable we create that same standard box but with a height of 40 so we can start to define our available paths. If the box is walkable we also want to set a mouseEvent so that we can select it. Finally we add these items to our isoScene.

Actionscript:
  1. for(var i:int = 0; i <pathGrid.numCols; i++)
  2. {
  3.     for(var j:int = 0; j <pathGrid.numRows; j++)
  4.     {
  5.         var node:Node = pathGrid.getNode(i, j);
  6.         var box:IsoBox = new IsoBox();
  7.  
  8.         if (node.walkable)
  9.         {
  10.             box.setSize(cellSize, cellSize, 0);
  11.             box.addEventListener(MouseEvent.CLICK, onGridItemClick);
  12.         }
  13.         else
  14.         {
  15.             box.setSize(cellSize, cellSize, 40);
  16.         }
  17.        
  18.         box.moveTo(i * cellSize, j * cellSize, 0);
  19.         isoScene.addChild(box);
  20.     }
  21. }

Another item within the drawGrid function is our playerHelper. We are only using this playerHelper so that we can get it's coordinates to follow along in papervision. We set him to the same size as our box items.

Actionscript:
  1. playerHelper.setSize(cellSize, cellSize, 10);

The next important step is setting up a way to have our viewport inside of our isoScene. We first create a nice wrapper for our viewport which is a native IsoSprite object. We then associate our viewport as one of the sprites inside of our isoSprite.

Actionscript:
  1. isoSprite = new IsoSprite();
  2. isoSprite.sprites = [viewport];
  3. isoScene.addChild(isoSprite);

Notice that we add our sprites kind of like we add filters for a movieclip. We are passing it an array.

Actionscript:
  1. //isoSprite.sprites = [viewport,moreStuff] - pass in an array of objects

Now lets see what happens when a grid item is clicked. First we gather the information about where we want to go. We gather that by getting the item that was clicked and getting its x & y positions divided by the cellSize. Then we give pathGrid.setEndNode those coordinates. Next we gather the information about where our playerHelper currently is divided by the cellSize and pass that information to pathGrid.setStartNode.

Actionscript:
  1. protected function onGridItemClick(evt:ProxyEvent):void
  2.         {
  3.             var box:IsoBox = evt.target as IsoBox;
  4.            
  5.             //Get and set End Nodes (where are we going)
  6.             var xpos:int = (box.x)/cellSize
  7.             var ypos:int = Math.floor(box.y / cellSize)
  8.             pathGrid.setEndNode(xpos,ypos );
  9.  
  10.             //Get and set Start Node (where are we now)
  11.             xpos = Math.floor(playerHelper.x / cellSize);
  12.             ypos = Math.floor(playerHelper.y / cellSize);
  13.             pathGrid.setStartNode(xpos, ypos);
  14.  
  15.             //Find our path
  16.             findPath();
  17.         }

Finally we call findPath(). This is the fun part. First we create a new instance of AStar and gather the path information that we gathered when we ran the onGridItemClick function.

We can now run through that loop and get each x and y portion of that loop. We simply add a tween with a delay that is the same time as our speed. This will allow you to see each move and when it is complete it will start it's next move.

Actionscript:
  1. protected function findPath():void
  2. {
  3.     var astar:AStar = new AStar();
  4.     var speed:Number = .3;
  5.     if(astar.findPath(pathGrid))
  6.     {
  7.         path = astar.path;
  8.     }
  9.    
  10.     for (var i:int = 0; i <path.length; i++)
  11.     {
  12.         var targetX:Number = path[i].x * cellSize;
  13.         var targetY:Number = path[i].y * cellSize;
  14.        
  15.         Tweener.addTween(playerHelper, { x:targetX, y:targetY, delay:speed * i , time:speed, transition:"linear" } );
  16.     }
  17. }

We now just need to look at how to sort the papervision with the as3isolib objects

Inside of our onRenderTick function which is an override from BasicView we use this to render our isoScene which is part of as3isolib and change the x,y coordinates of our sphere. We are basically following around the screenX and screenY of our playerHelper. The next and very important part of this is the depth sorting. We are pulling the depth at all times from the playerHelper object and assigning our isoSprite (which has our viewport in it) to that depth. Now we can watch as our 3D objects find their pretty little paths and sort without issue.

Actionscript:
  1. override protected function onRenderTick(event:Event = null):void
  2. {
  3.     super.onRenderTick(event);
  4.     isoScene.render();
  5.     sphere.x = playerHelper.screenX;
  6.     sphere.y = -playerHelper.screenY - 15;
  7.     isoScene.setChildIndex(isoSprite, isoScene.getChildIndex(playerHelper));
  8. }

Here is the full code:

Actionscript:
  1. package
  2. {
  3.     import as3isolib.display.IsoSprite;
  4.     import as3isolib.display.IsoView;
  5.     import as3isolib.display.primitive.IsoBox;
  6.     import as3isolib.display.primitive.IsoPrimitive;
  7.     import as3isolib.display.scene.IsoGrid;
  8.     import as3isolib.display.scene.IsoScene;
  9.     import bit101.AStar;
  10.     import bit101.Grid;
  11.     import bit101.Node;
  12.     import caurina.transitions.Tweener;
  13.     import flash.display.StageAlign;
  14.     import flash.display.StageScaleMode;
  15.     import flash.events.Event;
  16.  
  17.     import eDpLib.events.ProxyEvent;
  18.    
  19.     import flash.display.Sprite;
  20.     import flash.events.MouseEvent;
  21.    
  22.     import org.papervision3d.materials.WireframeMaterial;
  23.     import org.papervision3d.objects.primitives.Sphere;
  24.     import org.papervision3d.view.BasicView;
  25.  
  26.     public class Main extends BasicView
  27.     {
  28.         protected var cellSize:int = 50;
  29.         protected var pathGrid:Grid;
  30.         protected var playerHelper:IsoPrimitive;
  31.         protected var path:Array;
  32.         protected var isoSprite:IsoSprite;
  33.         protected var isoView:IsoView;
  34.         protected var isoScene:IsoScene;
  35.         protected var sphere:Sphere;
  36.        
  37.         public function Main()
  38.         {
  39.             super(800, 600, false);
  40.             stage.align = StageAlign.TOP_LEFT;
  41.             stage.scaleMode = StageScaleMode.NO_SCALE;
  42.            
  43.             create3D();
  44.             makeGrid();
  45.             startRendering();
  46.         }
  47.  
  48.         protected function create3D():void
  49.         {
  50.             sphere = new Sphere(new WireframeMaterial(),20);
  51.             scene.addChild(sphere);
  52.             camera.ortho = true;
  53.         }
  54.  
  55.         protected function makeGrid():void
  56.         {
  57.             pathGrid = new Grid(10, 10);
  58.             for(var i:int = 0; i <20; i++)
  59.             {
  60.                 pathGrid.setWalkable(Math.floor(Math.random() * 8) + 2,
  61.                                   Math.floor(Math.random() * 8)+ 2,
  62.                                   false);
  63.             }
  64.             drawGrid();
  65.         }
  66.        
  67.         protected function drawGrid():void
  68.         {
  69.             isoScene       = new IsoScene();
  70.             playerHelper    = new IsoPrimitive();
  71.             isoSprite     = new IsoSprite();
  72.             isoView         = new IsoView();
  73.  
  74.             for(var i:int = 0; i <pathGrid.numCols; i++)
  75.             {
  76.                 for(var j:int = 0; j <pathGrid.numRows; j++)
  77.                 {
  78.                     var node:Node = pathGrid.getNode(i, j);
  79.                     var box:IsoBox = new IsoBox();
  80.  
  81.                     if (node.walkable)
  82.                     {
  83.                         box.setSize(cellSize, cellSize, 0);
  84.                         box.addEventListener(MouseEvent.CLICK, onGridItemClick);
  85.                     }
  86.                     else
  87.                     {
  88.                         box.setSize(cellSize, cellSize, 40);
  89.                     }
  90.                    
  91.                     box.moveTo(i * cellSize, j * cellSize, 0);
  92.                     isoScene.addChild(box);
  93.                 }
  94.             }
  95.  
  96.             //Set properties for player helper
  97.             playerHelper.setSize(cellSize, cellSize, 10);
  98.            
  99.             //Set properties for isoView
  100.             isoView.setSize(stage.stageWidth, stage.stageHeight);
  101.            
  102.             //Set proper position for viewport
  103.             viewport.x = -stage.stageWidth / 2;
  104.             viewport.y = -stage.stageHeight / 2;
  105.  
  106.             //Add viewport to the isoSprite
  107.             isoSprite.sprites = [viewport];
  108.            
  109.             //Add the isoSprite and playerHelper to the isoScene
  110.             isoScene.addChild(isoSprite);
  111.             isoScene.addChild(playerHelper);
  112.            
  113.             //Add the isoScene to the isoView
  114.             isoView.addScene(isoScene);
  115.            
  116.             //Add the isoView to the stage
  117.             addChild(isoView);
  118.         }
  119.  
  120.         protected function onGridItemClick(evt:ProxyEvent):void
  121.         {
  122.             var box:IsoBox = evt.target as IsoBox;
  123.            
  124.             //Get and set End Nodes (where are we going)
  125.             var xpos:int = (box.x)/cellSize
  126.             var ypos:int = Math.floor(box.y / cellSize)
  127.             pathGrid.setEndNode(xpos,ypos );
  128.  
  129.             //Get and set Start Node (where are we now)
  130.             xpos = Math.floor(playerHelper.x / cellSize);
  131.             ypos = Math.floor(playerHelper.y / cellSize);
  132.             pathGrid.setStartNode(xpos, ypos);
  133.  
  134.             //Find our path
  135.             findPath();
  136.         }
  137.  
  138.         protected function findPath():void
  139.         {
  140.             var astar:AStar = new AStar();
  141.             var speed:Number = .3;
  142.             if(astar.findPath(pathGrid))
  143.             {
  144.                 path = astar.path;
  145.             }
  146.            
  147.             for (var i:int = 0; i <path.length; i++)
  148.             {
  149.                 var targetX:Number = path[i].x * cellSize;
  150.                 var targetY:Number = path[i].y * cellSize;
  151.                
  152.                 Tweener.addTween(playerHelper, { x:targetX, y:targetY, delay:speed * i , time:speed, transition:"linear" } );
  153.             }
  154.         }
  155.        
  156.         override protected function onRenderTick(event:Event = null):void
  157.         {
  158.             super.onRenderTick(event);
  159.            
  160.             //Render the isoScene
  161.             isoScene.render();
  162.            
  163.             //Place our 3D object at the correct location (following our playerHelper)
  164.             sphere.x = playerHelper.screenX;
  165.             sphere.y = -playerHelper.screenY - 15;
  166.            
  167.             /*
  168.            
  169.             Set the depth of our isoSprite which holds our viewport to the proper depth.
  170.            
  171.             NOTE: as3isolib objects - the depth sorting is done automatically,
  172.             we just need to tap into that
  173.            
  174.             */
  175.            
  176.             isoScene.setChildIndex(isoSprite, isoScene.getChildIndex(playerHelper));
  177.         }   
  178.     }
  179. }

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to StumbleUpon Stumble This Post

Adding XML to the Papervision Coverflow

Papervision Coverflow XML feed

As a simple addition to yesterday's coverflow post, I wanted to show the same example but with loading images via XML. For simplicity sake the XML is loaded and parsed all in the main file.

The structure for our XML is very simple:

XML:
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <data>
  3.     <image><![CDATA[images/image1.jpg]]></image>
  4.     <image><![CDATA[images/image2.jpg]]></image>
  5.     <image><![CDATA[images/image3.jpg]]></image>
  6.     <image><![CDATA[images/image5.jpg]]></image>
  7.     <image><![CDATA[images/image4.jpg]]></image>
  8.     <image><![CDATA[images/image6.jpg]]></image>
  9.     <image><![CDATA[images/image7.jpg]]></image>
  10. </data>

We simply load our XML file with BulkLoader

Actionscript:
  1. protected function loadXML():void
  2. {
  3.     bulkInstance = new BulkLoader("bulkInstance");     
  4.     bulkInstance.add(xmlPath);
  5.     bulkInstance.addEventListener(BulkProgressEvent.COMPLETE, onXMLReady);
  6.     bulkInstance.start();
  7. }

Parse the results, now adding the images to the BulkLoader:

Actionscript:
  1. protected function onXMLReady(evt:BulkProgressEvent):void
  2. {
  3.     bulkInstance.removeEventListener(BulkProgressEvent.COMPLETE, onXMLReady);
  4.     bulkInstance.addEventListener(BulkProgressEvent.COMPLETE, onImagesReady);
  5.    
  6.     var xml:XML = bulkInstance.getXML(xmlPath);
  7.     var xmlList:XMLList = xml.image;
  8.    
  9.     for (var i:int = 0; i <xmlList.length(); i++)
  10.     {
  11.         var imagePath:String = String(xmlList[i])
  12.         bulkInstance.add(imagePath);
  13.        
  14.         //Add path to array for later access
  15.         images.push(imagePath);
  16.     }
  17.    
  18.     //Set our number of items based on how many images we load
  19.     numItems = images.length;
  20. }

When our images are ready we can continue the process of setting up our coverflow. But now using the images we just loaded for our materials.

Actionscript:
  1. var mat:BitmapMaterial  = new BitmapMaterial(bulkInstance.getBitmapData(images[i]));

It's that simple. Be sure to let us know if you find this useful and are able to use it in a project.

Here is the full code:

Actionscript:
  1. package
  2. {
  3.     import br.com.stimuli.loading.BulkLoader;
  4.     import br.com.stimuli.loading.BulkProgressEvent;
  5.     import flash.display.Sprite;
  6.     import flash.events.MouseEvent;
  7.     import flash.filters.GlowFilter;
  8.     import gs.easing.Quint;
  9.     import gs.TweenLite;
  10.     import org.papervision3d.events.InteractiveScene3DEvent;
  11.     import org.papervision3d.materials.BitmapMaterial;
  12.     import org.papervision3d.objects.DisplayObject3D;
  13.     import org.papervision3d.objects.primitives.Plane;
  14.     import org.papervision3d.view.BasicView;
  15.    
  16.     /**
  17.      * ...
  18.      * @author Charlie Schulze, charlie[at]woveninteractive[dot]com
  19.      * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  20.      */
  21.    
  22.     public class Main extends BasicView
  23.     {
  24.         protected var planes:Array = [];
  25.         protected var images:Array = [];
  26.         protected var numItems:Number;
  27.         protected var currentItem:Number = 3;
  28.         protected var angle:Number = 25;       
  29.         protected var rightBtn:Sprite;
  30.         protected var leftBtn:Sprite;
  31.         protected var xmlPath:String = "xml/imageXML.xml";
  32.         protected var bulkInstance:BulkLoader;
  33.        
  34.         public function Main():void
  35.         {
  36.             //Make sure that your scene is set to interactive
  37.             super(640, 480, true, true);
  38.             loadXML();
  39.         }
  40.        
  41.         //First load our XML
  42.         protected function loadXML():void
  43.         {
  44.             bulkInstance = new BulkLoader("bulkInstance");     
  45.             bulkInstance.add(xmlPath);
  46.             bulkInstance.addEventListener(BulkProgressEvent.COMPLETE, onXMLReady);
  47.             bulkInstance.start();
  48.         }
  49.        
  50.         //When our xml is ready parse and load our images
  51.         protected function onXMLReady(evt:BulkProgressEvent):void
  52.         {
  53.             bulkInstance.removeEventListener(BulkProgressEvent.COMPLETE, onXMLReady);
  54.             bulkInstance.addEventListener(BulkProgressEvent.COMPLETE, onImagesReady);
  55.            
  56.             var xml:XML = bulkInstance.getXML(xmlPath);
  57.             var xmlList:XMLList = xml.image;
  58.            
  59.             for (var i:int = 0; i <xmlList.length(); i++)
  60.             {
  61.                 var imagePath:String = String(xmlList[i])
  62.                 bulkInstance.add(imagePath);
  63.                
  64.                 //Add path to array for later access
  65.                 images.push(imagePath);
  66.             }
  67.            
  68.             //Set our number of items based on how many images we load
  69.             numItems = images.length;
  70.         }
  71.        
  72.         //Images are finished loading we can now create our papervision coverflow
  73.         protected function onImagesReady(evt:BulkProgressEvent):void
  74.         {
  75.             init();
  76.         }
  77.        
  78.         protected function init():void
  79.         {
  80.             createChildren();
  81.             createNavigation();
  82.             animate();
  83.             startRendering();
  84.         }
  85.         protected function createChildren():void
  86.         {
  87.             for (var i:int = 0; i <numItems; i++)
  88.             {
  89.                 //Grab our bitmapData from the bulkLoader using our array of image paths as our key
  90.                 var mat:BitmapMaterial  = new BitmapMaterial(bulkInstance.getBitmapData(images[i]));
  91.                 mat.interactive         = true;
  92.                 mat.smooth     = true;
  93.                 var plane:Plane         = new Plane(mat, 280, 351, 4, 4);
  94.                
  95.                 planes.push(plane);
  96.                
  97.                 //Click straight to any plane
  98.                 plane.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, onPlaneClick);
  99.                
  100.                 //Set an id to target current item
  101.                 plane.id = i;
  102.                
  103.                 //Add plane to the scene
  104.                 scene.addChild(plane);
  105.             }
  106.            
  107.             camera.zoom = 50;
  108.         }
  109.        
  110.         protected function onPlaneClick(evt:InteractiveScene3DEvent):void
  111.         {
  112.             currentItem = evt.target.id;
  113.             animate();
  114.         }
  115.        
  116.         //Animate the coverflow left / right based off of currentItems
  117.         protected function animate():void
  118.         {
  119.             for (var i:int = 0; i <planes.length; i++)
  120.             {
  121.                 var plane:Plane = planes[i];
  122.                
  123.                 //Each if statement will adjust these numbers as needed
  124.                 var planeX:Number = 0;
  125.                 var planeZ:Number = -50;
  126.                 var planeRotationY:Number = 0
  127.  
  128.                 //Place  & Animate Center Item
  129.                 if (i == currentItem)
  130.                 {
  131.                     planeZ     = -300
  132.                    
  133.                     TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  134.                 }
  135.                
  136.                 //Place & Animate Right Items
  137.                 if(i> currentItem) 
  138.                 {
  139.                     planeX     = (i - currentItem + 1) * 120;
  140.                     planeRotationY   = angle + 10 * (i - currentItem);
  141.                    
  142.                     TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  143.                 }
  144.                
  145.                 //Place & Animate Left Items
  146.                 if (i <currentItem)
  147.                 {
  148.                     planeX     = (currentItem - i + 1) * -120;
  149.                     planeRotationY   = -angle - 10 * (currentItem - i);
  150.                    
  151.                     TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  152.                 }
  153.             }
  154.         }
  155.        
  156.         /*
  157.          * Everything below this point is just for creating the buttons and
  158.          * setting button events for controlling the coverflow.
  159.          */
  160.  
  161.         protected function createNavigation():void
  162.         {
  163.             //Create / Add Buttons
  164.             rightBtn = createButton();
  165.             leftBtn = createButton();
  166.                
  167.             addChild(leftBtn);
  168.             addChild(rightBtn);
  169.            
  170.             //Add button listeners
  171.             rightBtn.buttonMode = true;
  172.             leftBtn.buttonMode = true;
  173.             rightBtn.addEventListener(MouseEvent.CLICK, buttonClick);
  174.             leftBtn.addEventListener(MouseEvent.CLICK, buttonClick);
  175.                        
  176.             //Place buttons on stage
  177.             rightBtn.x    = stage.stageWidth - 20;
  178.             leftBtn.x       = 20;
  179.             rightBtn.y    =  stage.stageHeight / 2;
  180.             leftBtn.y       =  (stage.stageHeight / 2) + 20;
  181.             leftBtn.rotation    = 180;
  182.         }
  183.        
  184.         //Button actions
  185.         protected function buttonClick(evt:MouseEvent):void
  186.         {
  187.             switch (evt.target)
  188.             {
  189.                 case rightBtn:
  190.                 currentItem ++
  191.                 break;
  192.                
  193.                 case leftBtn:
  194.                 currentItem --;
  195.                 break;
  196.             }
  197.            
  198.             //Don't allow any number lower than 0 or past max so there
  199.             //is always a center item
  200.            
  201.             if (currentItem <0)
  202.             {
  203.                 currentItem = 0;
  204.             }
  205.             if (currentItem> (planes.length - 1))
  206.             {
  207.                 currentItem = planes.length - 1;
  208.             }
  209.            
  210.             //Call animation
  211.             animate();
  212.         }
  213.        
  214.         //Creates a simple arrow shape / returns the sprite
  215.         protected function createButton():Sprite
  216.         {
  217.             var btn:Sprite = new Sprite();
  218.            
  219.             btn.graphics.beginFill(0x333333);
  220.             btn.graphics.moveTo(0, 0);
  221.             btn.graphics.lineTo(0, 20);
  222.             btn.graphics.lineTo(10, 10);
  223.             btn.graphics.lineTo(0, 0);
  224.             btn.graphics.endFill();
  225.             btn.filters = [new GlowFilter(0xFFFFFF,1,10,10,3)]
  226.             return btn;
  227.         }
  228.     }
  229. }

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to StumbleUpon Stumble This Post

A Simple Papervision Coverflow

There are several great AS3 / Papervision Coverflows out there but today I set out to create one in it's simplest form. There are no bells and whistles, just a stripped down coverflow with it's core functionality. It's up to you to add an XML feed, Flickr feed, or setup your images in an array and load them the way you want to. This is only meant to be a clean jumping off point.

In the download I have included 2 versions. One with left / right buttons and one without. Both versions you can select the items in the coverflow to navigate.

The heart of this coverflow app is a lot like some of the others. We need to calculate the x and rotation of the center item, left items, and right items are, then animate accordingly. This is the same way that John Dyer animates his coverflow.

Actionscript:
  1. for (var i:int = 0; i <planes.length; i++)
  2. {
  3.     var plane:Plane = planes[i];
  4.    
  5.     //Each if statement will adjust these numbers as needed
  6.     var planeX:Number = 0;
  7.     var planeZ:Number = 20;
  8.     var planeRotationY:Number = 0
  9.  
  10.     //Place  & Animate Center Item
  11.     if (i == currentItem)
  12.     {
  13.         planeZ     = -300
  14.        
  15.         TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  16.     }
  17.    
  18.     //Place & Animate Right Items
  19.     if(i> currentItem) 
  20.     {
  21.         planeX     = (i - currentItem + 1) * 120;
  22.         planeRotationY   = angle + 10 * (i - currentItem);
  23.        
  24.         TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  25.     }
  26.    
  27.     //Place & Animate Left Items
  28.     if (i <currentItem)
  29.     {
  30.         planeX     = (currentItem - i + 1) * -120;
  31.         planeRotationY   = -angle - 10 * (currentItem - i);
  32.        
  33.         TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  34.     }
  35. }

For this simple version of coverflow you have two ways of navigating to items.

Selecting a plane to jump right to that item

Actionscript:
  1. plane.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, onPlaneClick);
  2.  
  3. protected function onPlaneClick(evt:InteractiveScene3DEvent):void
  4. {
  5.     currentItem = evt.target.id;
  6.     animate();
  7. }

Or using left / right buttons to navigate one item at a time:

Actionscript:
  1. rightBtn.addEventListener(MouseEvent.CLICK, buttonClick);
  2. leftBtn.addEventListener(MouseEvent.CLICK, buttonClick);
  3.  
  4. protected function buttonClick(evt:MouseEvent):void
  5. {
  6.     switch (evt.target)
  7.     {
  8.         case rightBtn:
  9.         currentItem ++
  10.         break;
  11.        
  12.         case leftBtn:
  13.         currentItem --;
  14.         break;
  15.     }
  16.    
  17.     //Don't allow any number lower than 0 or past max so there
  18.     //is always a center item
  19.    
  20.     if (currentItem <0)
  21.     {
  22.         currentItem = 0;
  23.     }
  24.     if (currentItem> (planes.length - 1))
  25.     {
  26.         currentItem = planes.length - 1;
  27.     }
  28.    
  29.     //Call animation
  30.     animate();
  31. }

On to the full source code. This version includes the left / right buttons.

Actionscript:
  1. package
  2. {
  3.     import flash.display.DisplayObject;
  4.     import flash.display.Sprite;
  5.     import flash.events.Event;
  6.     import flash.events.MouseEvent;
  7.     import flash.filters.GlowFilter;
  8.     import gs.easing.Quint;
  9.     import gs.TweenLite;
  10.     import org.papervision3d.events.InteractiveScene3DEvent;
  11.     import org.papervision3d.materials.BitmapFileMaterial;
  12.     import org.papervision3d.objects.DisplayObject3D;
  13.     import org.papervision3d.objects.primitives.Plane;
  14.     import org.papervision3d.view.BasicView;
  15.    
  16.     /**
  17.      * ...
  18.      * @author Charlie Schulze, charlie[at]woveninteractive[dot]com
  19.      * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  20.      */
  21.    
  22.     public class Main extends BasicView
  23.     {
  24.         protected var planes:Array = [];
  25.         protected var numItems:Number = 7;
  26.         protected var currentItem:Number = 3;
  27.         protected var angle:Number = 25;
  28.        
  29.         protected var mat:BitmapFileMaterial;
  30.         protected var rightBtn:Sprite;
  31.         protected var leftBtn:Sprite;
  32.        
  33.         public function Main():void
  34.         {
  35.             //Make sure that your scene is set to interactive
  36.             super(640, 480, true, true);
  37.            
  38.             init();
  39.         }
  40.         protected function init():void
  41.         {
  42.             createChildren();
  43.             createNavigation();
  44.             animate();
  45.             startRendering();
  46.         }
  47.         protected function createChildren():void
  48.         {
  49.             //Create Material
  50.             mat             = new BitmapFileMaterial("images/iPhone-back2.png");
  51.             mat.smooth   = true;
  52.             mat.interactive = true;
  53.             for (var i:int = 0; i <numItems; i++)
  54.             {
  55.                 var plane:Plane = new Plane(mat, 177, 334, 4, 4);
  56.                 planes.push(plane);
  57.                
  58.                 //Click straight to any plane
  59.                 plane.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, onPlaneClick);
  60.                
  61.                 //Set an id to target current item
  62.                 plane.id = i;
  63.                
  64.                 //Add plane to the scene
  65.                 scene.addChild(plane);
  66.             }
  67.            
  68.             camera.zoom = 60;
  69.         }
  70.        
  71.         protected function onPlaneClick(evt:InteractiveScene3DEvent):void
  72.         {
  73.             currentItem = evt.target.id;
  74.             animate();
  75.         }
  76.        
  77.         //Animate the coverflow left / right based off of currentItems
  78.         protected function animate():void
  79.         {
  80.             for (var i:int = 0; i <planes.length; i++)
  81.             {
  82.                 var plane:Plane = planes[i];
  83.                
  84.                 //Each if statement will adjust these numbers as needed
  85.                 var planeX:Number = 0;
  86.                 var planeZ:Number = -50;
  87.                 var planeRotationY:Number = 0
  88.  
  89.                 //Place  & Animate Center Item
  90.                 if (i == currentItem)
  91.                 {
  92.                     planeZ     = -300
  93.                    
  94.                     TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  95.                 }
  96.                
  97.                 //Place & Animate Right Items
  98.                 if(i> currentItem) 
  99.                 {
  100.                     planeX     = (i - currentItem + 1) * 120;
  101.                     planeRotationY   = angle + 10 * (i - currentItem);
  102.                    
  103.                     TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  104.                 }
  105.                
  106.                 //Place & Animate Left Items
  107.                 if (i <currentItem)
  108.                 {
  109.                     planeX     = (currentItem - i + 1) * -120;
  110.                     planeRotationY   = -angle - 10 * (currentItem - i);
  111.                    
  112.                     TweenLite.to(plane, 1, { rotationY:planeRotationY,x:planeX,z:planeZ, ease:Quint.easeInOut } );
  113.                 }
  114.             }
  115.         }
  116.        
  117.         /*
  118.          * Everything below this point is just for creating the buttons and
  119.          * setting button events for controlling the coverflow.
  120.          */
  121.  
  122.         protected function createNavigation():void
  123.         {
  124.             //Create / Add Buttons
  125.             rightBtn = createButton();
  126.             leftBtn = createButton();
  127.                
  128.             addChild(leftBtn);
  129.             addChild(rightBtn);
  130.            
  131.             //Add button listeners
  132.             rightBtn.buttonMode = true;
  133.             leftBtn.buttonMode = true;
  134.             rightBtn.addEventListener(MouseEvent.CLICK, buttonClick);
  135.             leftBtn.addEventListener(MouseEvent.CLICK, buttonClick);
  136.                        
  137.             //Place buttons on stage
  138.             rightBtn.x    = stage.stageWidth - 20;
  139.             leftBtn.x       = 20;
  140.             rightBtn.y    =  stage.stageHeight / 2;
  141.             leftBtn.y       =  (stage.stageHeight / 2) + 20;
  142.             leftBtn.rotation    = 180;
  143.         }
  144.        
  145.         //Button actions
  146.         protected function buttonClick(evt:MouseEvent):void
  147.         {
  148.             switch (evt.target)
  149.             {
  150.                 case rightBtn:
  151.                 currentItem ++
  152.                 break;
  153.                
  154.                 case leftBtn:
  155.                 currentItem --;
  156.                 break;
  157.             }
  158.            
  159.             //Don't allow any number lower than 0 or past max so there
  160.             //is always a center item
  161.            
  162.             if (currentItem <0)
  163.             {
  164.                 currentItem = 0;
  165.             }
  166.             if (currentItem> (planes.length - 1))
  167.             {
  168.                 currentItem = planes.length - 1;
  169.             }
  170.            
  171.             //Call animation
  172.             animate();
  173.         }
  174.        
  175.         //Creates a simple arrow shape / returns the sprite
  176.         protected function createButton():Sprite
  177.         {
  178.             var btn:Sprite = new Sprite();
  179.            
  180.             btn.graphics.beginFill(0x333333);
  181.             btn.graphics.moveTo(0, 0);
  182.             btn.graphics.lineTo(0, 20);
  183.             btn.graphics.lineTo(10, 10);
  184.             btn.graphics.lineTo(0, 0);
  185.             btn.graphics.endFill();
  186.             btn.filters = [new GlowFilter(0xFFFFFF,1,10,10,3)]
  187.             return btn;
  188.         }
  189.     }
  190. }

That's it. This should provide a good base for you to build out your own unique coverflow.

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to StumbleUpon Stumble This Post


Follow WovenCharlie on Twitter

Flash and the City banner
2010 Flash And The City Speaker

RSS Feed