Add

Papervision + Tweener + AS3 – Flipping Banner


UPDATE: Since I'm having problems with the SWF embedding, download the files to preview. Also be sure to check out the newer version with PV3D 2.0

Here's a little simple and practical application I had to put together for work using papervision. Nothing to write home about. Just a real world example that proves how easy it is to add papervision to your daily workflow. All this does is load a set of images from an XML file and papervision transitions from one to the other by flipping the plane using Tweener.

Core class:

package com.hydrotik.pageflip{
 
	/**
	 * @author Donovan Adams
	 * @version Sept 16, 2007
	 * @description Papervision Page flip example
	 * 
	 */
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.text.StyleSheet;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFieldAutoSize;
	import flash.filters.BlurFilter;
 
	import caurina.transitions.Tweener;
 
	import com.hydrotik.utils.XMLManager;
	import com.hydrotik.pageflip.Flip;
	import com.hydrotik.pageflip.FlipEvent;
 
	public class Core extends Sprite {
 
		private var _scope:MovieClip;
 
		private var _stage:Stage;
 
		private var _url:String;
 
		private var _xml:XML;
 
		private var url:String;
 
		private var _hit:Sprite;
 
		public function Core(scope:MovieClip, stage:Stage):void {
			_scope = scope;
			_stage = stage;
			_url = _scope.loaderInfo.url;
			var xml:XMLManager = new XMLManager("../includes/admin/flippingbanner.xml");
			xml.addEventListener("evtXMLLoaded", onXMLComplete);
		}
 
 
		// --== Private Methods ==--
		private function onXMLComplete(event:Event):void {
			trace(":: onXMLComplete:");
			_xml = event.target.xml;
 
			var _oFlip:Flip = new Flip(_scope, _stage, this, _xml.banner.children(), _xml.attribute("seconds"));
			_oFlip.addEventListener(FlipEvent.COMPLETE, onCompleteHandler);
			_oFlip.addEventListener(FlipEvent.ON_FLIP, onFlipHandler);
 
			_hit = new Sprite();
			_hit.graphics.beginFill(0x660000, 0);
			_hit.graphics.drawRect(0, 0, 300, 156);
			_scope.addChild(_hit);
			_hit.addEventListener(MouseEvent.CLICK, onClickHandler);
 
			_hit.buttonMode = true;
			_hit.useHandCursor = true;
			_hit.mouseEnabled = true;
		}
 
		private function onClickHandler(event:MouseEvent):void {
			trace("url: " + url);
			var request:URLRequest = new URLRequest(url);
			try {
				navigateToURL(request, "_self");
			} catch (e:Error) {
				// handle error here
			}
		}
 
		private function onCompleteHandler(event:FlipEvent):void {
			trace(event);
			url = event.url;
		}
 
		private function onFlipHandler(event:FlipEvent):void {
			trace(event);
			url = event.url;
		}
 
	}
}

Flipping code:

package com.hydrotik.pageflip{
 
	/**
	 * @author Donovan Adams
	 * @version July 10, 2007
	 * @usage Example:<code></code>
	 * @description
	 * @history
	 * @sends
	 * @todo
	 * 
	 */
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.filters.BitmapFilter;
	import flash.filters.BitmapFilterQuality;
	import flash.filters.BlurFilter;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.display.*;
	import org.papervision3d.cameras.FreeCamera3D;
	import org.papervision3d.core.*;
	import org.papervision3d.core.geom.Vertex3D;
	import org.papervision3d.materials.InteractiveMovieAssetMaterial;
	import org.papervision3d.materials.BitmapFileMaterial;
	import org.papervision3d.materials.ColorMaterial;
	import org.papervision3d.objects.Plane;
	import org.papervision3d.scenes.InteractiveScene3D;
	import org.papervision3d.events.InteractiveScene3DEvent;
	import org.papervision3d.events.FileLoadEvent;
	import org.papervision3d.utils.*;
 
	import caurina.transitions.Tweener;
 
	import com.hydrotik.pageflip.FlipEvent;
 
	public class Flip extends EventDispatcher {
 
		private var _scope:Sprite;
 
		private var _stage:Stage;
 
		private var _oCore:*;
 
		private var _assetPath:String;
 
		private var container:Sprite;
 
		private var scene:InteractiveScene3D;
 
		private var camera:FreeCamera3D;
 
		private var _materialArray:Array;
 
		private var _planeArray:Array;
 
		private var _array:XMLList;
 
		private var _count:int = 0;
 
		private var _next:Plane;
 
		private var _prev:Plane;
 
		private var _shadowPlane:Plane;
 
		private var _loader:Sprite;
 
		private var url:String;
 
		private var _id:int;
 
		private var _seconds:int;
 
		public function Flip(scope:Sprite, stage:Stage, core:*, a:XMLList, assetPath:String = "../flashassets/", s:int = 10):void {
			_scope = scope;
			_stage = stage;
			_oCore = core;
			_array = a;
			_assetPath = assetPath;
			_seconds = s;
			_materialArray = [];
			_planeArray = [];
 
			// Add Container
			container = new Sprite();
			container.x = stage.stageWidth/2;
			container.y = stage.stageHeight/2;
			_scope.addChild( container );
 
			scene = new InteractiveScene3D( container );
 
			camera = new FreeCamera3D();
			camera.z = -500;
 
			_loader = new Sprite();
			_loader.graphics.beginFill(0x000000);
			_loader.graphics.drawRect(0, 0, 1, 4);
			_scope.addChild(_loader);
			_loader.x = (stage.stageWidth/2) - 50;
			_loader.y = (stage.stageHeight/2) - 2;
 
			var colorMaterial:ColorMaterial = new ColorMaterial(0x000000, .2);
			_shadowPlane = new Plane( colorMaterial, stage.stageWidth, 50, 6, 6);
			_shadowPlane.y = -150;
			_shadowPlane.z = 50;
			_shadowPlane.rotationX = -90;
			_shadowPlane.rotationY = -180;
			scene.addChild(_shadowPlane);
 
			var filter:BitmapFilter = getBitmapFilter();
			var myFilters:Array = new Array();
			myFilters.push(filter);
			_shadowPlane.container.filters = myFilters;
			_shadowPlane.container.alpha = 0;
 
			for (var i:int = 0; i < _array.length(); i++) {
				_materialArray[i] = new BitmapFileMaterial(_array[i].attribute('src'));
				_materialArray[i].doubleSided = false;
				_materialArray[i].smooth = true;
				_materialArray[i].addEventListener(FileLoadEvent.LOAD_PROGRESS, onFileProgress);
				_materialArray[i].addEventListener(FileLoadEvent.LOAD_COMPLETE, onFileComplete);
				_planeArray[i] = new Plane( _materialArray[i], stage.stageWidth, stage.stageHeight, 6, 6);
				scene.addChild( _planeArray[i] );
				_planeArray[i].name = i.toString();
				_planeArray[i].rotationY = -180;
				_planeArray[i].container.alpha = 0;
			}
 
 
			// render the scene once
			scene.renderCamera( camera );
		}
 
 
 
		private function flip(id:int):void {
			Tweener.addTween(_next.container, {
				alpha:0,
				time:1,
				transition:"easeoutquint"
			});
			Tweener.addTween([_next, _shadowPlane], {
				rotationY:180,
				time:1,
				transition:"easeoutquint",
				onComplete:onOldFlipDone
			});
 
			// Update Data
			_prev = _next;
			_id = (id == _array.length() - 1) ? 0 : id + 1;
			_next = _planeArray[_id];
			url = _array[_id].attribute('link');
 
			dispatchEvent(new FlipEvent(FlipEvent.ON_FLIP, _id, _next.container, url));
 
			Tweener.addTween(_next.container, {
				alpha:1,
				time:1,
				transition:"easeoutquint"
			});
			Tweener.addTween([_next], {
				rotationY:0,
				time:1,
				transition:"easeoutquint",
				onUpdate:draw,
				onComplete:onFlipDone
			});
			Tweener.addTween(camera, {
				z:-100,
				_bezier:[{z:-350}, {z:-100}],
				time:2,
				transition:"easeoutquint"
			});
		}
 
 
		private function onFileProgress(event:FileLoadEvent):void {
			trace("\t percentage: "+Math.round((event.bytesLoaded/event.bytesTotal)*100) + "%");
			var sec:Number = 100/_array.length();
			_loader.width = ((_count * sec) + ((event.bytesLoaded/event.bytesTotal) * sec));
		}
 
		private function onFileComplete(event:FileLoadEvent):void {
			trace("complete!");
			scene.renderCamera( camera );
			_count++;
			if (_count == _array.length()) {
				onImageQueueCompleteHandler();
			}
		}
 
		private function onImageQueueCompleteHandler():void {
			dispatchEvent(new FlipEvent(FlipEvent.COMPLETE, 0, _planeArray[0].container, _array[0].attribute('link')));
			Tweener.addTween(_loader, {
				alpha:0,
				time:.2,
				transition:"easeoutquint",
				onComplete:loaderFade
			});
 
 
			trace("** papervision queue complete!!");
			Tweener.addTween([_planeArray[0].container, _shadowPlane.container], {
				alpha:1,
				time:1,
				transition:"easeoutquint"
			});
			Tweener.addTween([_planeArray[0], _shadowPlane], {
				rotationY:0,
				time:1,
				transition:"easeoutquint",
				onUpdate:draw,
				onComplete:onFlipDone
			});
			Tweener.addTween(camera, {
				z:-100,
				time:1,
				transition:"easeoutquint"
			});
			_next = _planeArray[0];
 
			_count = -1;
 
			var myTimer:Timer = new Timer(_seconds * 1000);
			myTimer.addEventListener(TimerEvent.TIMER, timerHandler);
			myTimer.start();
		}
 
		public function timerHandler(event:TimerEvent):void {
			trace("timerHandler: " + event);
			_count = (_count == _array.length() - 1) ? 0 : _count + 1;
			flip(new Number(_count));
		}
 
		private function draw():void {
			scene.renderCamera( camera );
		}
 
		private function onFlipDone():void {
			trace("flip done!");
 
		}
 
		private function loaderFade():void {
			_scope.removeChild(_loader);
		}
 
		private function onOldFlipDone():void {
			trace("old flip done!");
			_prev.rotationY = -180;
			_shadowPlane.rotationY = 0;
		}
 
		private function getBitmapFilter():BitmapFilter {
			var blurX:Number = 5;
			var blurY:Number = 5;
			return new BlurFilter(blurX,blurY,BitmapFilterQuality.HIGH);
		}
	}
}

Papervision is constantly going through new revs so keep in mind this is not the most recent. You'll see the Flip custom event, and a little XML loading utility in the source. Note that the Core file is just the main class. It could be your main timeline for all intents and purposes. Also the loader calculates the total images. I added a shadow plane just for a slight touch but that would lend itself to a white background and fixed banner sizes. A little breathing room for the shadow would be good if you wanted to enhance the effect. It's just a jumping off point for more, so have fun! :)

Like I said, nothing too fancy. Enjoy!


Papervision Flipping Banner Source

The Discussion

see what everyone is saying

  • [...] an slightly similar note, Donovan Adams has examples of a flipping banner using Papervision3D and Tweener. Sources are [...]

  • felix September 19th, 2007 at 2:59 pm #2

    it keeps reloading the page when I click on the swf… (os x /firefox)

  • djdonovan September 19th, 2007 at 3:36 pm #3

    The links in the XML are set to go to this page. I didn't get a change to add a target window attribute to the xml doc.

  • Neo September 19th, 2007 at 9:29 pm #4

    It looks cool~

  • Jon Marston September 24th, 2007 at 11:12 pm #5

    Thanks for the example, very cool. One problem:
    The zip file example has one hardcoded path. I needed to change line 49 of core.as to be "var xml:XMLManager = new XMLManager("../includes/admin/flippingbanner.xml");"

  • djdonovan September 24th, 2007 at 11:21 pm #6

    Nothing wrong with changing the path. I never intended this to be completely plug and play, although I suppose it is for the most part. I invite everyone to modify this and expand on it.:)

  • saravanan October 25th, 2007 at 2:57 am #7

    Hi, is there way to return bitmap data seperately as u use in XMLManager class..

    that is we just pass the url and the BitmapManager class should return bitmapdata ..

    is it posible

    thanks in advance

  • djdonovan October 30th, 2007 at 11:49 am #8

    Not sure I follow you. I'm not using any bitmap object in the xml class. Are you referring to a custom event for loading Bitmaps into Papervision? This might be a question for the papervision list in using the BitmapFileMaterial class?

  • Tercüme bürosu October 30th, 2007 at 2:29 pm #9

    it keeps reloading the page when I click on the swf..

  • djdonovan October 30th, 2007 at 2:34 pm #10

    See above.

  • Andrei Potorac November 27th, 2007 at 12:03 pm #11

    Congrats for this amazing file! I've been searching for this for some time. :)

  • Andrei Potorac November 27th, 2007 at 1:07 pm #12

    I found a bug. In the flip constructor, you have a variable which is read instead of the variable from the XML for the seconds, so no matter what value you put in the XML for the seconds, it won't read it. You should remove this from the constructor:

    assetPath:String = "../flashassets/",

    :)

  • djdonovan November 27th, 2007 at 2:55 pm #13

    In Core line 59 should read:

    var _oFlip:Flip = new Flip(_scope, _stage, this, _xml.banner.children(), "", _xml.attribute("seconds"));

  • djdonovan December 10th, 2007 at 11:04 pm #14

    Papervision 2.0 example has been added here.

  • [...] an slightly similar note, Donovan Adams has examples of a flipping banner using Papervision3D and Tweener. Sources are [...]

Respond

get in on the action.

* Required

revatio efects buy lisinopril viagra order online erectile dysfunction medications I Need To Buy Viagra drugs on line cheap msm food allergies muscle building diet osteoporosis hormon ultram dosage levitra without prescription buy viagra in canada buy desyrel buy mexiletine buy phentermine online without prescription where to buy soma lithium carbonate women and viagra medications on line ultram er alprazolam no perscription viagra online without prescription type 2 diabetes diazepam pharmacology lower high blood pressure how to get big muscles discount dog products starlix buy deltasone health vitamins ultram dosage tooth whitening dentist buy pain meds now a reliever of arthritic pain hoodia patches cheap decadron reduce cholesterol naturally asthma control cheap generic viagra online fitness muscle online treatment for aids body building online course throat infection treatment increasing breast size naturally buy celebrex online buy antibiotics cheap online clomid testosterone booster patch nutritional diet for osteoporosis treating aids in africa blood pressure diet order vitamins order viagra online cymbalta vs lexapro xanax without prescription cheap pet health care buy prevacid buy prevacid soma 250 drug for nausea where to buy soma natural cure for erectile dysfunction ear pain right side back pain dog calming pills ordering viagra dental antibiotics antifungal strategies help the pain januvia cheap diabetes type 2 bronchitis diarrhea cimetidine dose alprazolam acne tips blood pressure buy cheap tooth whitening product prevacid online water pill buspirone dosage prescription phentermine buy beconase lower leg pain vitamins for women new antibiotic drug dog health care weight loss after baby skin cancer treatments high blood pressure yerba diet self help alcoholism benicar generic cure blood clot eye infections in dogs bph prostate family pharmacy zyban pharmacy atarax generic high blood pressure drug list buy xanax online buy natural antibiotics list how to white teeth avalide generic viagra cialis levitra medician for heart attacks phentermine prescription alcoholism new treatment help for depression heart failure medicine buy retin a buy levitra online with fast delivery body fat lose weight loss web sites buy nimotop herpes simplex new blood pressure drug how do a stop smoking flu shots herpes treatment enhance sexual performance effects of celexa viagra shop increase male volume treatment for chest pain cats bladder side effects clomid face wrinkles allegra klonopin effects relieve joint pain drugs that relieve pain new cat products human parasite ultram dosing tab tramadol carb blocker medication to stop smoking order viagra online in germany anxiety info ambien viagra gel use of xanax for anxiety online drugs without prescription weight loss health health ambien online buy viagra online cheap alternative medicine cholesterol mestinon blood pressure meds treatment parkinsons disease buy viagra without prescription methocarbamol effects pet health care information what is saw palmetto buy cialis online without a prescription flu drugs celebrex information gout cures buy orlistat on line sildenafil dosage blood pressure medication names ultram dosing order viagra canadian drug online big muscle fluconazole 150mg lasix cheap ashwagandha dosage side effects of ativan body acne treatment buying viagra online without prescription body building programs cat health care natural pet products viagra order body building tips high blood calcium level estradiol pill tips for weight loss back pain medications atenolol withdrawal vermox xanax dose antibiotics bronchitis cialis cialis information how to white teeth diabetes blood sugar levels pravastatin sleep disorders remedy viagra superactive diet pills hypnotherapy cds viagra cheep carisoprodol purchase cat anxiety buy alcoholism medications nausea cure how do a stop smoking relieve joint pain oral ketoconazole clonazepam pharma california cold flu calcium channel blocker hypertension prednisone allergy Cealis Lavetra effects of levitra professional anti allergic drug drugs for hiv body building online course dog ear problem super flu quickly stop smoking bad body odor atlas rx viagra abilify 10mg nolvadex 20mg hair loss treatment uk anti obesity chloramphenicol triphala sleep disorder treatment information on ambien remedy for hair loss when are beta blockers prescribed myasthenia gravis risperdal anxiety symptoms high blood pressure cure snoring chronic heart failure medicines valium with no prescription buy alcoholism medications generic pain medication alternative treatment arthritis diovan prescription latest diet pill effects of levitra professional clomid drug xanax without prescription online hair loss for men purchase viagra online hair loss products for men lamictal viagra online usa xenical no prescription pneumonia vs bronchitis prednisone 10 mg diflucan buy celebrex online anti fungus products endep liver infection treatment order indomethacin penis enlagement augmentin medication hair loss prevention treatment for yeast infection pyridium chest pain symptoms flovent generic valium with no prescription prevention of diabetes breast enhancement new york levitra do for men ginkgo biloba prescription lipitor klonopin zoloft order medication to aid in sleeping diabetes type 2 medicines for insomnia weight loss and fitness high blood pressure info purchase levitra online cialis on line health support discount prescription medications alprazolam no perscription how to purchase cialis acne free antifungal sinus women insomnia valium maximum dosage osteoporosis bone health buspar online discount cialis levitra viagra cure bronchitis prostate cancer treatment protonix overactive bladder medications skin cancer treatment effects klonopin yeast infection remedies fluconazole interaction canada online pharmacy viagra healthy women's vitamins expected weight loss with phentermine how to purchase cialis about cialis body building buy product how to buy cialis male erectile dysfunction femara drug topamax parkinson medications male bladder problems diabetes health care system haldol medication withdrawal zyrtec buy hyzaar cat hairball remedies cheap florinef lipitor use drugs for pain celebrex cealis lavetra Viagra Cialis Levitra buy nimotop how to increase fertility buy pain medicine online insomnia sleep problems cheapest place buy viagra online tooth whitening systems haldol medication information on levitra cialis advice bactroban price of drugs seroquel for anxiety malaria preventative effects of allegra body building info vytorin generic bladder problem solutions dog health help cialis cheap no prescription beta blockers bronchitis antibiotics back pain anti-fungal natural arthritis cures buying viagra online in britain penis development cheapest generic cialis snoring woman stretch penis purchase generic viagra virility gum viagra and sports buy proscar soma on line diet supplements that work breast enhancer pills how to enlarge breast buy cialis generic online dog bowel problems pet health information enhance breast acai alpha blocker medications cialis best on-line drugstore infection dog ears enhance sexual performance weight loss male sexual power cat health info clean dogs ears ultram used for gout medicines effective weight loss program improve sexual confidence cialis levitra viagra sildenafil kamagra cat skin disorders female sexual enhancement creams prozac on line bentyl drug diarrhea in pregnancy insomnia pills helping high blood pressure buy plendil lipitor use weight loss support group online buy plan b remedies for stomach ulcers cancer cure phentermine with no perscription best weight loss products online pain doctors buy vitamin a breast enhancer how to build muscle generic abilify free pain pills by mail breast enhancement products prostate cancer support accupril cymbalta medication small penis ramipril capsules depression symptoms treatment penis enhansment blood pressure drug names herpes medications to buy free smoking treatment online carisoprodol lasix drug depression and anxiety buy griseofulvin without prescription free weight loss tips klonopin pill viagra cialis levitra diet drug online enhancement breast atacand generic get viagra prescription online verapamil drug zyban what is hoodia overactive bladder in men buy tramadol cheap treatment for chronic fungal infection zoloft buy white spots on face pediatric diarrhea paxil information buy online cialis weight loss doctor online brain cancer treatment new weight loss drug levitra pro medication for depression relieve joint pain naturally enhancement breast health information bone health general drugs for hiv nexium drug premature ejaculation cure promethazine tablets treatment for dry skin erectile dysfunction cure online viagra without prescription best weight loss solutions drug allergies buy buy cialis online now cancer drug acessrx buy tooth whitening products parkinson disease medicine free hoodia