nintendo ds emulator for psp 3000 guitar chord chart printable desktop destroyer christmas version free download samsung moment vs htc hero vs palm pre wireless bridge linksys wrt54g2 cigarettes online how to install bluetooth dongle vista dodge charger forum dress up games for adults only free online jeep grand cherokee for sale xbox 360 secret achievements borderlands guitar tabs for hey there delilah mazda 3 speed turbo compaq laptops drivers free download winter olympics 2010 opening ceremonies tickets jeep wrangler for sale subaru impreza outback sport 2010 pontiac g8 gxp for sale canada laminate countertops price per square foot scanner software freeware mac tattoo ideas for girls galleries canon 7d firmware hack toyota yaris recall 2009 design your own wedding dress online game snowboard pants with suspenders tattoo removal cost estimate moviefone promotional code grasslands facts for kids notebook computers under 400 kawasaki atv repair manual download bmw forums e46 trucks for sale in pakistan pizza dough recipe for bread machine facebook chat emoticons ancient egyptian hieroglyphics for kids 2006 mazda 6 aftermarket parts bathroom wall tile ideas dodge viper srt 10 for sale rolex datejust price range famous people with dyslexia posters toyota tacoma prerunner 4x4 subaru forester 2010 accessories warcraft 3 image extractor 2 download student loan forgiveness obama nikon d90 video tutorial 1967 pontiac gto muscle car used porsche 911 for sale usa bathroom renovation ideas pictures 2005 kia sorento problems multiplayer rpgs for wii flash games 247 bike mania 4 kia soul price in egypt honda civic hatchback for sale software engineer salary india sony vaio laptops drivers chevrolet for sale medieval rpg flash games wedding invitations costco jaguar cars history infiniti g35 parts toyota center kennewick small bathroom renovation ideas pictures underwear drawer famous deaf people today satellite tv providers canada volkswagen passat for sale suzuki sx4 awd 2010 samsung mobile phones in india with price english dating sims for girls guitar tuner drop c carnival cruise fare codes mazda cx7 reviews 2009 auctions online michigan princess cut diamond and sapphire engagement rings satellite radio antenna booster fishing knots and rigs toyota recall list rav4 pants off dance off uk cheeky girls bob hope chrysler classic grassland animals pictures usb modem speed booster mitsubishi lancer forum malaysia keyboard stickers arabic cartridge world prices australia canon t1i video tips toyota tacoma recall rust frame how to debrand sony ericsson c905a wifi hyundai santa fe reviews 2009 samsung mythic a897 avery templates for business cards fishing reports california delta website builder freeware dvdfab 6 registration keygen mazda miata hardtop sale famous short friendship poems snowboarding jackets on sale in canada rolex watches for women bathroom cabinets and vanities ikea keyboard shortcuts symbols music note compaq evo drivers free download volkswagen beetle parts catalog snowboarding gloves grenade bruce laminate floors reviews cruise critic chrysler crossfire srt6 convertible suzuki oem motorcycle parts basketball plays flex offense snowboard boots and bindings canon powershot g11 accessories porsche cayenne 2010 model memory foam dog bed seen on tv cablevision channel guide bronx pontiac gto judge wallpaper suzuki sx4 crossover reviews camcorder buying guide india dress up who betty boop subaru legacy gt bathroom shower tile ideas volkswagen beetle accessories bmw financial services go green sweepstakes replica coach purses wholesale ticketmaster promo codes portrait photography tips lighting samsung led tv 6000 2001 chrysler town and country parts diagram hyundai sonata 2010 picture grassland animals and their adaptations bmw m3 gtr printer drivers epson r200 pontiac grand prix gxp mitsubishi outlander forum yamaha vintage snowmobiles lexus rx 350 recalls kia sorento 2011 canada funny winter solstice quotes dress up barbie kitchen glass tile backsplash pictures receiver hitch winch mitsubishi lancer forum canada subaru sti 2010 sedan basketball drills for 6 year olds saturn sl performance parts used mitsubishi evo 9 for sale desktop destroyer 2 grassland animals facts guitar chord chart pdf rpg maker vx resources pack porsche forums usa saturn astra performance parts skype download for blackberry 8900 truck accessories san antonio texas guitar pro 6 torrent download ventrilo server status script on your website bluetooth headset for ipod touch 3rd gen replica louis vuitton belts buy converse shoes online cheap sony vegas movie studio 9 keygen compaq presario cq60 drivers for windows 7 laura ashley laminate flooring installation instructions dodge caliber problems compaq presario f700 drivers for windows xp lands end coupon code 20 off gift ideas for boyfriend microsoft templates online desktop destroyer game christmassy rolex oyster perpetual cosmograph daytona price bridesmaid dresses plus size indesign templates for business cards free logo creator freeware volkswagen beetle engine codes northface denali jackets on sale for women wedding cakes and prices desktop destroyer toyota and lexus recall 2009 free dating websites for single parents samsung eternity games saw video game walkthrough guide subaru impreza wrx for sale in pa compaq presario cq50 drivers for vista bmw financial services phone number mitsubishi lancer parts diagram subaru outback 2010 price toyota recall list november 2009 bathroom ideas for small spaces software testing tutorial download toyota floor mat recall list bmw x5 aftermarket parts opelousas general hospital baby pictures samsung plasma tv calibration hand blown glass pipes bongs tattoos for girls on hip 2010 volkswagen gti reliability nissan leaf specs software engineering interview questions with answers truck games download free bmw usa factory exact replica louis vuitton handbags sample wedding vows write your own compaq c700 infinity ward host migration problems honda accord crosstour commercial song rolex daytona price 2009 kia cars usa sawgrass mills mall directory wedding dresses 2010 pictures rolex watches models bmw x5 e70 forum templates for resumes and cover letters cablevision channel guide nj cadillac cts v coupe toyota corolla parts porsche boxster spyder 2011 compaq presario v3000 drivers for vista gps maps free download cyprus xbox 360 repair center animation factory rapidshare hd screensavers for mac free printer ink cartridges refill playstation roms torrent roses are red jokes basketball reference police scanner radio frequencies warcraft 3 frozen throne cd key buy rolex serial numbers chart best backpacks for college 2009 hyundai accent 2010 pictures jeanstar jeans retailers 2010 porsche panamera hybrid bathroom accessories unlimited tattoo fonts cursive generator infinity ward nat settings winter 2010 olympics opening ceremony jeeps for sale in alabama skype for blackberry curve 8520 wallpaper desktop widescreen suzuki 2010 motorcycles release date limewire pro free mac os x bluetooth headphones ps3 use printer offline error processing command scanner reviews 2009 cnet guitar scales pdf free download toyota financial repossession software testing life cycle ppt kia motors philippines kitchen islands on wheels opel astra 2010 model lexus suv hybrid 2010 hyundai santa fe forum uk laminate countertops home depot subaru baja tonneau wow cataclysm beta download samsung omnia i910 mazda 323 forum honda accord forum malaysia subaru wrx 2010 pictures recipes for ground beef meatballs porsche cayenne 2010 spy shots play gamecube iso on wii usb trucks gone wild carp fishing games free online lexus rx 350 recall bathroom vanity ideas fishing boats for sale in california guitar hero online keyboard guitar center used gear pontiac solstice hardtop convertible wowhead gatherer database wireless router setup with comcast ford edge forum jeeps for sale by owner bathroom sinks modern microsoft bluetooth dongle vista driver hummer accessories in dubai volkswagen jetta tdi 2010 review perfume emporium uk kia forte koup turbo charger gamecube emulator mac os off road tires and wheels packages mazda tribute forum bathroom floor tile size trucks for sale by owner in florida gamecube emulator games playstation 2 emulator bios plugins jackets with fur hoods for men furniture factory outlet nj roses are red violets are blue love poems funny quotes and sayings for facebook dodge charger parts diagram toyota recall gas pedal sticking volkswagen beetle parts bathroom flooring ideas summer glau underwear marriage vows samples snowboard sizing chart by weight honda accord for sale cheap furniture liquidators baton rouge louisiana antique bicycles western flyer pocket tanks deluxe download free subaru legacy 2010 screensavers free downloads for phones rolex daytona gold egyptian love symbols skype video conference 3 way chrysler town and country parts diagram bicycle parts warehouse dvd decrypter windows 7 tattoos for guys helmet decals racing cablevision channel lineup bicycle outlet warehouse nissan cars for sale in sri lanka mitsubishi evo for sale mercedes benz forum singapore how much does siding cost per square foot pizza hut hawaii coupon code playstation support rolex watches price escuchar radio online mexico replica toy guns australia common chrysler pacifica problems volkswagen gti r playstation store redeem codes for psp rpg online games flash marriage statistics 2009 uk jacket size chart women music theory for dummies pdf bathroom designs for small spaces tattoo removal cost hyundai tiburon performance parts mitsubishi outlander 2009 accessories samsung solstice games free mazda parts diagram bridesmaid hairstyles pictures 2009 basketball court dimensions youth background music for video editing fake rolex submariner watch suzuki 50cc atv for sale backgrounds for computer for kids mitsubishi lancer for sale in bangalore 95 saturn sl2 parts pitbull protection kia sorento 2010 interior music theory worksheets note values gamecube emulator mac torrent laptop bags for men famous american artists 19th century mercedes sl amg wheels volkswagen parts people toyota brake recall 2009 opel astra diesel hybrid cameras at walmart canada pool table dimensions wiki designer indian wedding dresses dating sim games anime jeep golden eagle for sale zte modem drivers for windows 7 samsung rogue software for pc rolex watches truck paper classified driver software refacing fireplace pictures snowboard size chart for men desktopx themes toyota forklift parts online roses are red poems skype download for blackberry 8520 subaru outback 2010 accessories free laundromat business jaguar v12 performance parts compaq presario v2000 drivers for windows 7 apartments in atlanta ga based on income guitar pro torrent suzuki sx4 turbo famous sad love poems basketball court dimensions in feet used server racks atlanta kia motors philippines website bathroom remodeling ideas for small bathrooms famous french artists of the 19th century webmail hack software downloads free rolex oyster perpetual datejust xbox 360 oblivion cheats nikon coolpix s220 speed dating questions for men co ed episiode download jeans size chart furniture liquidators chicago il wallpaper borders for kids rooms mazda tribute reviews 2002 laminate flooring installation video motorola h500 samsung rogue verizon forum jewelry supplies wholesale nyc bluetooth software for windows xp sp3 plant cell structure worksheet mercedes benz e class convertible 2010 famous computer crime cases logo creator free download samsung rogue manual download contemporary bathroom lighting ideas free fake diploma software winter jackets for petite women tires plus coupon is samsung solstice wifi mattresses cheap juice plus ingredients dating dress up games for girls mid length hair styles sealed cork floor tiles top 20 wedding ceremony entrance songs porsche 911 forum gmc sierra denali 2010 aluminum siding brakes for sale mazda5 review subwoofer enclosures diy keyboards for macbook pro canon printers troubleshooting download ruby rom mazda 626 parts diagram pontiac g8 gxp review recipes for pork chops underwear for men pouch portfolio lighting fixtures lowes bathroom vanities and cabinets lowes roses are red violets are blue poems for children roses are red violets are blue funny love strelske igre download multiplayer wedding invitations templates free update evolution soccer download free printers for sale at costco dress up celebrities boys and girls samsung solstice apps download clothes over bros dresses program dish tv remote codes snowboard sizing chart for kids xbox 360 elite specs antivirus torrent free microsoft office download full version ford models europe sony vegas download mac best perfumes with pheromones layouts for bikerornot auto loan calculator excel spreadsheet designer wedding dresses games for girls free spanish games pes download subaru tribeca owners forum warcraft 3 cd key samsung dlp tv repair manual jeans size chart boys sven download tattoo cursive lettering quickheal antivirus software swf games snow harley davidson oem parts fiche samsung eternity manual download printer drivers epson r300 ford escape mileage sony ericsson k800i symbols on screen download cd key for cod2 guitar chord linux netbook distro comparison backgrounds for powerpoint microsoft snowboarding gloves with built in wrist guards wireless n gigabit router reviews subaru club volkswagen passat diesel problems bathroom vanities discount toronto juniper credit samsung led tv manual bluetooth headset ps3 pass key garden twist pattern ground turkey recipes food network famous poems about death of a loved one cables unlimited wireless usb adapter kit chevrolet camaro price in india digital cable filter trucks for sale by owner in illinois shirt design template funny marriage quotes and sayings jaguar xj220 for sale compaq presario r3000 drivers download handheld gps comparison guide black hair cuts compaq presario cq60 drivers for vista cadillac srx 2010 commercial song jeeps for sale cigarette rolling machine auto parts warehouse coupon code rock island auction samsung lcd tv models india pizza sauce recipes epicurious summer fashion internships gmc acadia forum samsung eternity software for mac nail art step step cadillac srx commercial song falling samsung pn50b650 plasma tv mitsubishi tv manual download auction sites like ebay dress up celebrities for girls best type of carpeting for stairs


Tag Archive for 'Papervision Cube'

12. Animation using Tweener

**Update
This tutorial has been updated using TweenLite and the most recent papervision BasicView class.
view-update

Hi,

In this tutorial we're going to use Tweener to move a cube around. This will teach you basics of animation, and how to use Tweener (which is awesome).

The example that I've produced is this:

So, in this example our solid red cube is trying to stay inside our green wireframe cube. Every time the red cube gets itself positioned completley inside the green cube, the green cube moves.

Tweener is the package which is smoothly moving the red cube around. The Tweener package is also firing the event to move the green cube when the tween is complete.

1: To start off, you'll need Tweener. You can download it here if you don't already have it: http://code.google.com/p/tweener/

Once you've got tweener, either add the source directory containing the "caurina" folder to your project's classpaths, or add the caurina folder into your current project.

2: Import tweener - Add this line to your imports:

import caurina.transitions.Tweener;

3: Add a Tween. You can add tweens to any parameter of any object. The Tweener package will gradually change any parameter in your code to a new value over time, so only numeric values will work nicely. Anyway, you can read a load more about tweener at the google code page above.

To add a tween, we use the code

Tweener.addTween(object, {parameter1: value, parameter2: value2, time: X, 
transition:"transition", onComplete: functionname});

This may look a little bit confusing at first, but it's really simple. Let's show you a real example..

Tweener.addTween(cube, { x: 1000, z: 500, time: 2, onComplete: randomize } );

The line above will add a tween. This tween will change the values "x" and "y" on the object "cube" to 1000 and 500 respectively. It will smoothly change the values over a period of 2 seconds and once the tween is complete and the cube.x is 1000 and cube.y is 500, it will trigger the "randomize" function.

Experiment with more ways to tween your objects. You can apply tweens to anything, including cameras, lights, rotations, sizes and camera zooms. Any numerical value you can think of.

Here is my source code (Uses latest version of my base class):

Actionscript:
  1. package 
  2. {
  3.      import org.papervision3d.lights.PointLight3D;
  4.      import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
  5.      import org.papervision3d.materials.utils.MaterialsList;
  6.      import org.papervision3d.materials.WireframeMaterial;
  7.      import org.papervision3d.objects.primitives.Cube;
  8.      import org.papervision3d.objects.primitives.Plane;
  9.  
  10.      import caurina.transitions.Tweener;
  11.  
  12.      public class Main extends PaperBase
  13.      {
  14.           private var cube:Cube;
  15.           private var cube2:Cube;
  16.           private var mat:FlatShadeMaterial = new FlatShadeMaterial(new PointLight3D(), 0xFFFFFF, 0xFF0000);
  17.           private var mat2:WireframeMaterial = new WireframeMaterial(0x00FF00);
  18.           private var plane:Plane = new Plane(null, 2000, 2000, 10, 10);
  19.  
  20.           public function Main()
  21.           {
  22.                init(600, 300);
  23.           }
  24.  
  25.           override protected function init3d():void
  26.           {
  27.                cube = new Cube(new MaterialsList( { all: mat } ), 100, 100, 100);
  28.                cube.y = 0;
  29.                cube2 = new Cube(new MaterialsList( { all: mat2 } ), 100, 100, 100);
  30.                cube2.y = 0;
  31.                cube2.x = 1000;
  32.                cube2.z = 1000;
  33.                plane.material.lineColor = 0x777777;
  34.                plane.material.doubleSided = true;
  35.                plane.pitch(90);
  36.                plane.y = -50;
  37.                default_scene.addChild(plane);
  38.                default_scene.addChild(cube);
  39.                default_scene.addChild(cube2);
  40.                Tweener.addTween(cube, { x:1000, z:1000, time:2, onComplete: randomize } );
  41.                default_camera.x = 0;
  42.                default_camera.z = 1000;
  43.                default_camera.y = 1000;
  44.           }
  45.  
  46.           public function randomize():void
  47.           {
  48.                var xp:Number = (Math.random() * 2000) - 1000;
  49.                var yp:Number = (Math.random() * 2000) - 1000;
  50.                Tweener.addTween(cube, { x:xp, z:yp, time:2, onComplete: randomize } );
  51.                cube2.x = xp;
  52.                cube2.z = yp;
  53.           }
  54.  
  55.           override protected function processFrame():void
  56.           {
  57.                default_camera.lookAt(cube);
  58.           }
  59.      }
  60. }

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

Panorama Viewer

*FIXED!!*

Here's a really simple example, all it does is texture a sphere and rotate it depending on what the camera is doing:

Click Here (1.3Mb download so I didn't embed this one)

Source Code (Uses the Base Class):

Actionscript:
  1. /**
  2. * ...
  3. * @author Luke Mitchell
  4. * @version 1
  5. */
  6.  
  7. package  {
  8. \timport org.papervision3d.materials.BitmapFileMaterial;
  9. \timport flash.events.MouseEvent;
  10. \timport org.papervision3d.materials.ColorMaterial;
  11. \timport org.papervision3d.materials.utils.MaterialsList;
  12. \timport org.papervision3d.objects.primitives.Cube;
  13. \t
  14. \tpublic class Main extends PaperBase {
  15. \t\t
  16. \t\tpublic var materials:MaterialsList = new MaterialsList(
  17. \t\t{
  18. \t\t\tfront: new BitmapFileMaterial("http://papervision2.com/wp-content/pano/s1.gif"),
  19. \t\t\tback: new BitmapFileMaterial("http://papervision2.com/wp-content/pano/s3.gif"),
  20. \t\t\tleft: new BitmapFileMaterial("http://papervision2.com/wp-content/pano/s4.gif"),
  21. \t\t\tright: new BitmapFileMaterial("http://papervision2.com/wp-content/pano/s2.gif"),
  22. \t\t\ttop: new ColorMaterial(0x000000),
  23. \t\t\tbottom: new ColorMaterial(0x000000)
  24. \t\t});
  25. \t\tpublic var cubemap:Cube = new Cube(materials, 2000, 2000, 900, 5, 5, 5,Cube.ALL);
  26. \t\t
  27. \t\tpublic function Main() {
  28. \t\t\tinit(600,300);
  29. \t\t\tcubemap.x = 0;
  30. \t\t\tcubemap.y = 0;
  31. \t\t\tcubemap.z = 0;
  32. \t\t\t
  33. \t\t\tdefault_scene.addChild(cubemap);
  34. \t\t\tdefault_camera.z = 0;
  35. \t\t\tdefault_camera.x = 0;
  36. \t\t\tdefault_camera.y = 0;
  37. \t\t\tdefault_camera.lookAt(cubemap);
  38. \t\t\t
  39. \t\t\tdefault_camera.zoom = 5;
  40. \t\t\tstage.addEventListener(MouseEvent.MOUSE_WHEEL, mWheel);
  41. \t\t}
  42. \t\t
  43. \t\tpublic function mWheel(e:MouseEvent):void {
  44. \t\t\tdefault_camera.zoom += e.delta / 5;
  45. \t\t\tif (default_camera.zoom <5) {
  46. \t\t\t\tdefault_camera.zoom = 5;
  47. \t\t\t}else if (default_camera.zoom> 20) {
  48. \t\t\t\tdefault_camera.zoom = 20;
  49. \t\t\t}
  50. \t\t}
  51. \t\t
  52. \t\toverride protected function processFrame():void {
  53. \t\t\tcubemap.yaw( -((stage.mouseX - (stage.width / 2)) / stage.width)*4);
  54. \t\t\tdefault_camera.rotationX = -((stage.mouseY - (stage.height / 2)) / stage.height) * (Math.sqrt(default_camera.zoom*6));
  55. \t\t}
  56. \t}
  57. }

You can use this for pretty much any panoramic image, just change the image url and tweak it a bit :)

-Luke

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

11. Advanced Interactivity 2

**UPDATE
This tutorial has been updated
view-update

This tutorial will show you how to handle full interactivity on an objects surface, just as if it's a normal movieclip.

For my example, I've made this. The red spot in the centre is a button. You can click it to toggle it's glow on and off. The other button will reveal how it works!

There are other ways to do this, but I think this way is the easiest and most hassle-free, and it's pretty fast.

I've super-commented the source code, so from reading the comments in the code you should be able to figure out exactly what's going on.

The basic idea is, you add the movie clip which is being used as the texture to the scene, but make it invisible. You then move it so that your mouse is over the correct part of the movieclip, when your mouse touches the texture on the 3d model. I think the "Show Movieclip" button on the cube above will explain better than I can :)

Actionscript:
  1. package  {
  2.     import flash.display.Bitmap;
  3.     import flash.display.MovieClip;
  4.     import flash.events.MouseEvent;
  5.     import flash.filters.GlowFilter;
  6.     import org.papervision3d.materials.MovieMaterial;
  7.     import org.papervision3d.materials.utils.MaterialsList;
  8.     import org.papervision3d.objects.primitives.Cube;
  9.     import org.papervision3d.events.InteractiveScene3DEvent;
  10.    
  11.     public class Main extends PaperBase {
  12.        
  13.         // This is the movieclip that we'll use as the texture.
  14.         private var movie:MovieClip = new MovieClip();
  15.        
  16.         // This movieclip will be completley transparent and will hold the
  17.         // texture movieclip, then move it to the correct loaction under the mouse.
  18.         private var movieParent:MovieClip = new MovieClip();
  19.        
  20.         // These are buttons that I'm going to add to the texture movieclip
  21.         private var button:MovieClip = new MovieClip();
  22.         private var showbutton:MovieClip = new MovieClip();
  23.        
  24.         // A "MovieMaterial" will use a movieclip as a texture.
  25.         private var mat:MovieMaterial;
  26.        
  27.         // The cube that we're going to texture..
  28.         private var cube:Cube;
  29.        
  30.         // This will import the file "E:/Papervision/images/showtex.jpg" to the project, and
  31.         // store the data in "ButtonIm". (This is the "Show Movieclip" Button)..
  32.         [Embed(source = "E:/Papervision/images/showtex.jpg")] private var ButtonIm:Class;
  33.        
  34.         public function Main() {
  35.             // Initiate, 400px wide, 400px tall..
  36.             init(400, 400);
  37.         }
  38.        
  39.         override protected function init3d():void {
  40.             // - See the prepareMovieclip function. This just builds the movieclip called "movie".
  41.             // You can use ANY movie clip for this..
  42.             prepareMovieclip();
  43.            
  44.             // Prepare out moviematerial. Make it animated and interactive.
  45.             mat = new MovieMaterial(movie, false, true);
  46.             mat.interactive = true;
  47.            
  48.             // Zoom in a bit..
  49.             default_camera.zoom = 5;
  50.            
  51.             // Prepare the cube.
  52.             cube = new Cube(new MaterialsList( { all: mat } ), 500, 500, 500, 4, 4, 4);
  53.             // Listen for when the mouse is moved over the cube.
  54.             // Trigger the mMove function when this happens.
  55.             cube.addEventListener( InteractiveScene3DEvent.OBJECT_MOVE, mMove);
  56.            
  57.             // Add the cube to the scene.
  58.             default_scene.addChild(cube);
  59.            
  60.             // The movieParent movieclip will hold the movieclip which is being used
  61.             // as the texture. It will then move depending on the mouse posirion.
  62.             movieParent.addChild(movie);
  63.             // Make it invisible.
  64.             movieParent.alpha = 0;
  65.            
  66.             // Add the movieParent movieclip to the stage.
  67.             addChild(movieParent);
  68.            
  69.         }
  70.        
  71.        
  72.         private function prepareMovieclip():void {
  73.            
  74.             // - This code will set up our movieclip which is going to be used
  75.             // as the texture for the cube.
  76.             // Draw Outline:
  77.             movie.graphics.beginFill(0xFFFFFF);
  78.             movie.graphics.drawRect(0, 0, 500, 500);
  79.             movie.graphics.endFill();
  80.             movie.graphics.beginFill(0x000000);
  81.             movie.graphics.drawRect(0, 0, 10, 500);
  82.             movie.graphics.drawRect(490, 0, 10, 500);
  83.             movie.graphics.drawRect(0, 0, 500, 10);
  84.             movie.graphics.drawRect(0, 490, 500, 10);
  85.             movie.graphics.endFill();
  86.            
  87.             // Draw Circular Button:
  88.             button.graphics.beginFill(0xBB0000);
  89.             button.graphics.drawCircle(0, 0, 50);
  90.             button.graphics.endFill();
  91.             button.x = 250;
  92.             button.y = 250;
  93.             button.buttonMode = true;
  94.            
  95.             // Load bitmap button texture:
  96.             var Bim:Bitmap = new ButtonIm();
  97.             // Draw "Show Movieclip" Texture:
  98.             showbutton.graphics.beginBitmapFill(Bim.bitmapData);
  99.             showbutton.graphics.drawRect(0,0,100,30);
  100.             showbutton.graphics.endFill();
  101.             showbutton.buttonMode = true;
  102.             showbutton.x = 380;
  103.             showbutton.y = 450;
  104.            
  105.             // Add the buttons to the movieclip
  106.             movie.addChild(showbutton);
  107.             movie.addChild(button);
  108.            
  109.             // -- Listen for the buttons to be clicked --
  110.             button.addEventListener(MouseEvent.CLICK, mClickButton);
  111.             showbutton.addEventListener(MouseEvent.CLICK, showHide);
  112.             // --
  113.         }
  114.        
  115.         private function showHide( e:MouseEvent ):void {
  116.             // The "Show Movieclip" button has been clicked
  117.             if (movieParent.alpha == 0) { // If it's invisible,
  118.                 movieParent.alpha = 0.2; // Make it slightly visible.
  119.             }else {
  120.                 movieParent.alpha = 0; // Or make it invisible again
  121.             }
  122.         }
  123.        
  124.         private function mClickButton(e:MouseEvent):void {
  125.             // The cental round button has been clicked.
  126.             if(button.name == "on"){
  127.                 button.filters = null;
  128.                 button.name = "off"
  129.             }else {
  130.                 button.filters = [new GlowFilter(0x000000, 1, 15, 15, 10, 1)];
  131.                 button.name = "on";
  132.             }
  133.         }
  134.        
  135.         private function mMove( e:InteractiveScene3DEvent ):void {
  136.             // This code is run when the mouse is moved on the cube.
  137.             // This will move the movieclip to the right place beneath
  138.             // the mouse.
  139.             movieParent.x = root.mouseX -e.x;
  140.             movieParent.y = root.mouseY -e.y;
  141.         }
  142.        
  143.         override protected function processFrame():void {
  144.             // Spin our cube a bit.
  145.             cube.yaw(0.25);
  146.             cube.pitch(0.25);
  147.         }
  148.        
  149.        
  150.     }
  151. }

The image that's embedded in the code can be found here: showtex.jpg

Have fun! More Examples coming soon.

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

10. Advanced Interactivity

**UPDATE
This tutorial has been updated:
Updates:
1) Removed InteractiveScene3DEvent and replaced it with standard MouseEvents
2) Updated to use papervision's BasicView.as class

view-update

Today we're going to learn how to handle more advanced interactivity. We'll be making something like this:

Click on a face of the cube to zoom into it. Click it again to make the cube spin again.

So, in this tutorial I'm going to show you exactly how to work out which material has been clicked on the cube and act accordingly.

If you haven't read it already, I strongly suggest that you read the Basic Interactivity tutorial first or you'll probably miss something.

Ok, so on to the code.

Firstly we'll want six materials to apply to each face of the cube. Here are mine, although you can create whatever materials you like:

Actionscript:
  1. private var frontMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/front.jpg");
  2.         private var backMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/back.jpg");
  3.         private var leftMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/left.jpg");
  4.         private var rightMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/right.jpg");
  5.         private var topMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/top.jpg");
  6.         private var bottomMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/bottom.jpg");

So, in this code I'm just loading six images from my server to use as each face.

Also, add the following declaration beneath the texture declarations to hold our Cube object:

Actionscript:
  1. private var cube:Cube;

Now we need to set up the 3d initiation code. In this code we will firstly set all of our materials as interactive, and then give each of our materials a name. This is VERY important to be able to easily find out which material has been clicked. If we didn't give each material a name then we wouldn't be able to easily work out which face has been clicked.

So, add the following code to your init3d() function:

Actionscript:
  1. override protected function init3d():void {
  2.             // We need to be able to identify each side. We'll do this
  3.             // by asssigning names to each material. During this process
  4.             // we'll also make the materials interactive.
  5.             frontMaterial.interactive = true;
  6.             frontMaterial.name = "front";
  7.             backMaterial.interactive = true;
  8.             backMaterial.name = "back";
  9.             leftMaterial.interactive = true;
  10.             leftMaterial.name = "left";
  11.             rightMaterial.interactive = true;
  12.             rightMaterial.name = "right";
  13.             topMaterial.interactive = true;
  14.             topMaterial.name = "top";
  15.             bottomMaterial.interactive = true;
  16.             bottomMaterial.name = "bottom";
  17.             // ---------------------------------------------
  18.            
  19.             cube = new Cube(new MaterialsList( {
  20.                 front: frontMaterial,
  21.                 back: backMaterial,
  22.                 left: leftMaterial,
  23.                 right: rightMaterial,
  24.                 top: topMaterial,
  25.                 bottom: bottomMaterial
  26.                 } ), 500, 500, 500, 3, 3, 3);
  27.             cube.addEventListener( InteractiveScene3DEvent.OBJECT_PRESS, onPress);
  28.             default_scene.addChild(cube);
  29.         }

So, In this code, we've set each material as interactive, given each one a sensible name, and initialised our cube with the materials assigned to the correct faces.

We then add an event listener to trigger the "onPress" event when the cube is clicked, then finally we add the cube to the scene.

We've now got a cube with six materials on it listening for a click event.

Now, the code which will let us work out which face has been clicked:

Actionscript:
  1. private function onPress( e:InteractiveScene3DEvent ):void {
  2.     switch(e.face3d.material.name) {
  3.         case "front":
  4.             // This code will be run when the front face is clicked
  5.         break;
  6.         case "back":
  7.             // This code will be run when the back face is clicked
  8.         break;
  9.         case "left":
  10.             // This code will be run when the left face is clicked
  11.         break;
  12.         case "right":
  13.             // This code will be run when the right face is clicked
  14.         break;
  15.         case "top":
  16.             // This code will be run when the top face is clicked
  17.         break;
  18.         case "bottom":
  19.             // This code will be run when the bottom face is clicked
  20.         break;
  21.     }
  22. }

Pretty self explanitary. The "e" variable in this code holds lots of data about the click event, including which material has been clicked, so, because we know which material is on each face, we can tell by the materials name which face has been clicked!

With a little bit of code, you can make a nice spinning cube gallery like the example above:

Here is my final code, have fun!

Actionscript:
  1. package  {
  2.    
  3.     import flash.display.DisplayObject;
  4.     import org.papervision3d.materials.BitmapFileMaterial;
  5.     import org.papervision3d.materials.utils.MaterialsList;
  6.     import org.papervision3d.events.InteractiveScene3DEvent;
  7.     import org.papervision3d.objects.primitives.Cube;
  8.    
  9.     public class Main extends PaperBase {
  10.        
  11.         private var frontMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/front.jpg");
  12.         private var backMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/back.jpg");
  13.         private var leftMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/left.jpg");
  14.         private var rightMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/right.jpg");
  15.         private var topMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/top.jpg");
  16.         private var bottomMaterial:BitmapFileMaterial = new BitmapFileMaterial("http://papervision2.com/wp-content/pvTex/bottom.jpg");
  17.        
  18.         private var targetrotationX:Number = 0;
  19.         private var targetrotationY:Number = 0;
  20.         private var targetrotationZ:Number = 0;
  21.        
  22.         private var tweening:Boolean = false;
  23.        
  24.         private var cube:Cube;
  25.        
  26.         public function Main() {
  27.             init(400, 400);
  28.         }
  29.        
  30.         override protected function init3d():void {
  31.             // We need to be able to identify each side. We'll do this
  32.             // by asssigning names to each material. During this process
  33.             // we'll also make the materials interactive.
  34.             frontMaterial.interactive = true;
  35.             frontMaterial.name = "front";
  36.             backMaterial.interactive = true;
  37.             backMaterial.name = "back";
  38.             leftMaterial.interactive = true;
  39.             leftMaterial.name = "left";
  40.             rightMaterial.interactive = true;
  41.             rightMaterial.name = "right";
  42.             topMaterial.interactive = true;
  43.             topMaterial.name = "top";
  44.             bottomMaterial.interactive = true;
  45.             bottomMaterial.name = "bottom";
  46.             // ---------------------------------------------
  47.            
  48.             cube = new Cube(new MaterialsList( {
  49.                 front: frontMaterial,
  50.                 back: backMaterial,
  51.                 left: leftMaterial,
  52.                 right: rightMaterial,
  53.                 top: topMaterial,
  54.                 bottom: bottomMaterial
  55.                 } ), 500, 500, 500, 3, 3, 3);
  56.             // Listen for the click:
  57.             cube.addEventListener( InteractiveScene3DEvent.OBJECT_PRESS, onPress);
  58.             // Add to scene:
  59.             default_scene.addChild(cube);
  60.         }
  61.        
  62.         private function onPress( e:InteractiveScene3DEvent ):void {
  63.             // If the cube has been moved to the front:
  64.             if (tweening) {
  65.                 // Let it rotate again
  66.                 tweening = false;
  67.             }else {
  68.                 // Find which rotation we need to be able to see
  69.                 // the face image:
  70.                 switch(e.face3d.material.name) {
  71.                     case "front":
  72.                         targetrotationX = 0;
  73.                         targetrotationY = 180;
  74.                         targetrotationZ = 0;
  75.                         tweening = true;
  76.                     break;
  77.                     case "back":
  78.                         targetrotationX = 0;
  79.                         targetrotationY = 0;
  80.                         targetrotationZ = 0;
  81.                         tweening = true;
  82.                     break;
  83.                     case "left":
  84.                         targetrotationX = 0;
  85.                         targetrotationY = -90;
  86.                         targetrotationZ = 0;
  87.                         tweening = true;
  88.                     break;
  89.                     case "right":
  90.                         targetrotationX = 0;
  91.                         targetrotationY = 90;
  92.                         targetrotationZ = 0;
  93.                         tweening = true;
  94.                     break;
  95.                     case "top":
  96.                         targetrotationX = 90;
  97.                         targetrotationY = 0;
  98.                         targetrotationZ = 0;
  99.                         tweening = true;
  100.                     break;
  101.                     case "bottom":
  102.                         targetrotationX = -90;
  103.                         targetrotationY = 0;
  104.                         targetrotationZ = 180;
  105.                         tweening = true;
  106.                     break;
  107.                 }
  108.             }
  109.         }
  110.        
  111.         override protected function processFrame():void {
  112.             if (tweening) {
  113.                 // If a face has been clicked
  114.                 if (default_camera.zoom <6.8) {
  115.                     // If the camera isn't zoomed enough then zoom in a bit more:
  116.                     default_camera.zoom += Math.sqrt(6.8-default_camera.zoom)/5;
  117.                 }
  118.                
  119.                 // Test each rotation and rotate it towards the target rotation:
  120.                 // X axis:
  121.                 if (cube.rotationX <targetrotationX) {
  122.                     cube.rotationX += Math.sqrt(targetrotationX-cube.rotationX);
  123.                     cube.rotationX = Math.round(cube.rotationX);
  124.                 }else if (cube.rotationX> targetrotationX) {
  125.                     cube.rotationX -= Math.sqrt(cube.rotationX-targetrotationX);
  126.                     cube.rotationX = Math.round(cube.rotationX);
  127.                 }
  128.                 // Y axis:
  129.                 if (cube.rotationY <targetrotationY) {
  130.                     cube.rotationY += Math.sqrt(targetrotationY-cube.rotationY);
  131.                     cube.rotationY = Math.round(cube.rotationY);
  132.                 }else if (cube.rotationY> targetrotationY) {
  133.                     cube.rotationY -= Math.sqrt(cube.rotationY-targetrotationY);
  134.                     cube.rotationY = Math.round(cube.rotationY);
  135.                 }
  136.                 // Z axis:
  137.                 if (cube.rotationZ <targetrotationZ) {
  138.                     cube.rotationZ += Math.sqrt(targetrotationZ-cube.rotationZ);
  139.                     cube.rotationZ = Math.round(cube.rotationZ);
  140.                 }else if (cube.rotationZ> targetrotationZ) {
  141.                     cube.rotationZ -= Math.sqrt(cube.rotationZ-targetrotationZ);
  142.                     cube.rotationZ = Math.round(cube.rotationZ);
  143.                 }
  144.             }else {
  145.                 // If the camera is zoomed in, it shouldn't be now
  146.                 if (default_camera.zoom> 2) {
  147.                     // So zoom out a bit.
  148.                     default_camera.zoom -= Math.sqrt(default_camera.zoom-2)/5;
  149.                 }
  150.                
  151.                 // Rotate the cube a bit:
  152.                 cube.rotationX += 2;
  153.                 cube.rotationY += 2;
  154.                
  155.                 // Make sure that we dont "wind up" the rotation
  156.                 if (cube.rotationX>= 360) cube.rotationX = 0;
  157.                 if (cube.rotationY>= 360) cube.rotationY = 0;
  158.             }
  159.         }
  160.     }
  161. }

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


Follow papervision2 on Twitter

Flash and the City banner
2010 Flash And The City Speaker

RSS Feed