xbox live gold membership generator chrysler financial make a payment jeans for big thighs small waist desktop backgrounds for macbook pro windows xp internet backgammon os x snow leopard server serial number canon powershot sx20 is price in malaysia summer 2010 fashion internships in new york snowboarding games online free guitar hero world tour unlock all songs cheat buy commercial truck tires online yamaha atv parts yamaha outboards troubleshooting samsung lcd tv problems black screen dress up barbie games to play satellite tv for pc elite edition password subaru outback 2010 review canada diamond solitaire engagement rings monster truck games online for kids watch summer heights high episode 1 online samsung lcd tv troubleshooting no picture nikon d5000 prices in dubai limewire basic for mac os x bridezillas where are they now karee rpg maker 2003 rtp cheap dresses for juniors online wireless headphones for ipod touch 1g youtube malayalam movies xbox 720 pics xbox 360 hard drive transfer kit gamestop student doctor network interview feedback compaq mini netbook with intel atom processor used pool tables for sale in michigan download auctioneer addon for wow chrysler town and country parts mitsubishi lancer evolution x mr pizza hut coupons online codes 2001 chrysler sebring convertible parts boots online shopping ireland canon rebel eos manual ds6041 honda civic hatchback parts for sale skype download for blackberry curve 8520 famous love quotes from the notebook healthy pizza dough no yeast pizza hut menu with prices canada wedding invitation wording divorced parents mdi reader download jar software free download for mobile travelocity gnome commercial song cruises only coupons best screensavers for mac snow leopard xbox 360 games on demand hack student loans without cosigner and no credit dvd ripper for mac freeware jcpenney furniture outlet atlanta ga cocktail dresses online cheap youtube video to mp3 converter for mac paid summer internships new york city radiohead tour 2010 north america dodge journey 2009 sxt housecall antivirus helmets for motorcycles in india free playstation network card generator bathroom shower tiles pictures nintendo ds roms free download english canon rebel xti vs nikon d5000 best wireless headphones for tv listening porsche 911 turbo for sale craigslist snowflake patterns crochet backpacks for college radio disney live stream wireless n router review cnet truck mount carpet cleaning machines for sale subaru 22b sti for sale commercial carpet steam cleaning machines hairstyles for women over 60 pictures bride wars soundtrack listen wireless n router range comparison free elementary career interest inventory bmw m3 for sale cheap tires plus locations in florida next radiohead tour 2010 pontiac grand prix gtp supercharged transmission websites like craigslist personals samsung i8000 omnia ii reviews gps maps for blackberry playstation 3 gamestop trade in value barcode scanner java api laptops cheapest uk project portfolio management software open source radiohead tour 2010 uk dating simulation games for girls online porsche carrera gt for sale in us pontiac gto judge 1969 for sale land rover freelander parts diagram samsung plasma tv calibration settings honda motorcycle parts warehouse honda generators eu2000i rpg maker vx sprite generator download snowboarding jackets on sale for women replica daft punk helmets for sale portfolio lighting replacement parts playstation 3 network card generator 2010 mazda 3 replacement parts infinity ward nat strict pc jeep wrangler unlimited for sale in iowa rpg maker vx activation code free nissan skyline gtr for sale in florida dvdfab registration key generator dvdfab 6 keygen download download snowboarding games for pc porsche cayenne 2010 prices hp psc 1610 scanner software for vista autotune 5 download for windows princess cut diamond engagement rings cheap free strip blackjack canon rebel xsi tutorial video murray riding lawn mower parts diagram nintendo ds roms download free xbox live ban wave finished glassjaw tour dates 2010 buy cigarettes online paypal mazda 626 manual transmission guitar pro 6 release date bmw m3 2010 prices mazda reviews mercedes benz amg black edition 2011 cadillac cts v coupe motorcycle repair manuals for free subaru forester parts catalog wedding reception invitation wording examples skype for mac snow leopard movies online streaming new moon dvd ripper for mac snow leopard playstation emulator vista download software architecture in practice ppt shirt printing machines for sale hyundai santa fe 2010 release date samsung mythic a897 price in india rolex prices datejust flash player 9 free download firefox marlboro cigarettes online usa radio stations online free hip hop mitsubishi lancer evolution for sale used volkswagen jetta sportwagen tdi for sale honda financial services phone number handbags leather manufacturer mazda tribute parts diagram wedding vows traditional catholic tattoo quote ideas for girls logo creator software free download canon rebel xti vs nikon d3000 nissan skyline gtr for sale in california tools download free skype video conference 3 people templates for powerpoint games kids snow boots clearance uk jeep grand cherokee reviews 2000 design your own wedding dress online free game xbox tips toyota prius prices paid canon s90 review ken rockwell radiohead tour dates 2010 furnitureland south bankruptcy skinny jeans for men on sale crochet snowflake patterns free pizza hut menu prices us design your own wedding dress for free wedding shower favors homemade 1971 volkswagen beetle convertible for sale wireless bridge linksys wrt160n snowboarding gloves or mittens gps coordinates conversion formula mercedes benz parts online uk jaguar xk8 performance parts snowboard pants sale nikon d60 manual download free land rover defender 110 for sale travelers insurance commercial song worry mobile satellite internet service providers tattoo wedding rings pictures furniture liquidators denver download logo maker freeware sony ereader touch backlight download desktop destroyer 2 chicken carnage how to make pizza dough without yeast and baking powder skype download vista 64 bit cypress hill torrent summer paid internships 2010 design your own engagement ring tiffany prom dresses for prom 2010 modem commands us robotics xbox 360 e73 repair guide roses are red poems funny crocodile monitor lizards for sale marriage counseling infidelity wedding dresses pictures for men dvdfab 6 platinum registration key master bathroom renovation ideas warcraft 3 cd key finder tires plus corporate headquarters sony reader vs kindle vs nook sony vegas 9 serial number free toyota corolla parts catalog playstation emulator mac os x snow leopard guitar tuner drop c tuning mitsubishi lancer ralliart specs skype phone wifi dress up games and makeover games and cooking games tattoo ideas for girls wrist yamaha baby grand piano for sale compaq presario c700 drivers for xp suzuki sidekick parts manual templates for resumes for teachers samsung mythic a897 black wifi porsche cayenne forum italian pizza recipes dough nintendo ds emulator for iphone 3g golf digest hot list 2010 irons toyota oem parts discount winter olympics history wow cataclysm worgen druid forms famous movie quotes from the 80s gps maps free download tomtom wedding ceremony songs christian sony vaio recovery disk free download laminate flooring installation instructions pergo caribbean weather forecast subaru impreza wrx sti for sale in canada toyota forklift parts catalog skype emoticons hidden volkswagen tiguan review top gear cable modem hacking software sofas direct from factory wholesale handbags designer inspired kawasaki mule parts diagram antique harley davidson motorcycle parts sample resume restaurant waitress monitor audio rx8 test logo design freeware download honda civic 2010 price egyptian arts and crafts for kids example career essays tattoos ideas for girls pictures flooring options for screened porch toyota recall gas pedals honda accord forum 7th gen toyota camry recall 2009 guitar tabs for beginners acoustic mazda rx8 performance parts tattoos quotes for guys guitar tuner widget os x suzuki gsxr motorcycles for sale xbox 360 games torrent tracker volkswagen tiguan 2010 release date used mercedes amg for sale yamaha vmax motorcycles for sale harley davidson sportster parts and accessories snowboard pants men toyota corolla floor mat recall football fanatics coupon code 20 off sofa beds for sale in san diego ca sony psp 3000 games free download dresses for prom under 100 dollars latin tattoo quote ideas subaru wrx parts catalog grassroots lobbying examples mac logo creator freeware hyundai genesis coupe review chevrolet tahoe police package for sale toyota center seating chart 3d download gps maps europe lawnmower man game jaguar cars for sale on ebay warcraft 3 cheats reign of chaos suzuki grand vitara parts online subaru forester forum singapore saturn ion performance parts xbox 360 transfer kit gamestop jeans size chart forever 21 beginner guitar chord chart printable winter olympics 2010 tv coverage mercedes parts hardware temperature monitor windows 7 mitsubishi outlander 2010 commercial song craftsman tool boxes on wheels illuminated bathroom mirrors with shelf subaru baja turbo mpg dresses to wear to a wedding games for girls flight attendant mile high club sony vegas free download for mac suzuki samurai engine swap kit jeep grand cherokee 2011 release date yamaha atvs for sale cheap toyota venza 2010 hybrid 1998 mitsubishi eclipse spyder parts guitar chord chart finger position guitar tabs for sweet home alabama for beginners toyota recalls rav4 famous movie quotes quiz toyota body parts used guest bathroom color ideas mercedes benz sl55 amg price xbox 360 elite vs ps3 specs jeanstar jeans macys toyota recall list accelerator installing laminate flooring on stairs video harley davidson accessories for dogs guitar chord chart finger placement free soccer drills for 4 year olds dodge charger srt8 for sale used perfume outlet online snow leopard hackintosh laptop compaq presario v2000 laptop motherboard rpg maker vx resources faces warcraft 3 download free for mac tattoos for guys forearms kitchenaid dishwasher parts diagram mitsubishi parts oem guitar pro torrent mac toyota land cruiser parts and accessories modern wedding invitation wording examples lexus is 250 for sale by owner animation factory essential collection honda generators prices tattoo quote ideas for men famous funny poems about school software testing tutorials for beginners pdf chrysler 300 accessories canada cruises only coupon code garden of eden key west web cam summer internships for college students 2010 invoice templates free microsoft word jeep wrangler unlimited hardtop volkswagen gti 2010 price volkswagen beetle convertible pink mitsubishi evo 8 mr for sale winter jackets for men sale winter bells game cheat sony ericsson equinox reviews samsung moment vs htc hero comparison replica cowboy guns computer science resume objective dvdfab registration key 6 harley oem parts online 2000 jaguar s type parts clothes horse store samsung omnia i910 firmware update download snowflake patterns photoshop saturn vue transmission problems canon powershot a480 manual pdf biketoberfest 2009 pictures famous deaf people in history glass bongs online store gamecube emulator mac os x 2005 volkswagen beetle convertible for sale mitsubishi eclipse spyder body kits kia sportage 2008 problems coach shoes on sale at dillards wedding dresses pictures indian desktop wallpaper for macbook pro software manual testing interview questions hair color pictures highlights guitar chord chart poster famous short funny poems dvd shrink free download for mac mattress firm clearance center toyota tacoma lift kits 2wd world war 2 replica cap guns toyota camry parts for sale warcraft 2 tides of darkness mac download unblock facebook proxy at school ford trucks for sale in florida mitsubishi electric air conditioning remote control jeep grand cherokee 2011 video nissan versa hatchback reviews 2010 laminate flooring installation costs toyota camry 2010 recall mercedes e63 amg wagon for sale volkswagen passat cc 2010 famous american ceramic artists facebook layouts for mac empire carpeting reviews tattoo ideas for men quotes biker chicks photos college football recruiting rankings 2011 isuzu trooper engine diagram cable tv providers by zip code daft punk helmets for sale equalizer software mazda rx 8 r3 body kit replica cap guns snow white and the seven dwarfs story script linux commands list pdf free tattoo cursive lettering bathroom wall tile design ideas famous love poems sonnets tattoo script lettering alphabet satellite internet connection wwe dvd release schedule 2010 linux ubuntu beryl download free funny wedding vows write your own compaq presario c700 specifications movie replica airsoft guns compaq presario f700 drivers for windows 7 winter olympics history wiki summer heights high quotes jonah takalua used opel cars for sale in germany bathroom vanities cabinets wireless router booster homemade acoustic guitar scales beginners mercedes benz e63 amg coupe volkswagen parts diagrams software testing life cycle flow chart bicycles for sale at walmart toyota recall 2009 list apartments for rent in philadelphia no credit check why is flash flash revolution down used pool tables for sale dallas tx porsche boxster spyder 2010 guitar power chords chart t shirt dress sewing pattern youtube indian movies songs the jewelry exchange complaints hyundai elantra 2010 mpg compaq presario v6000 specs toyota tacoma used 4x4 mazda 626 parts online list of toyota recall september 2009 warcraft 3 cd key battlenet custom jeep cherokee bumpers famous poems about death and loss furniture factory outlet missouri suzuki sx4 forum toyota tacoma 2010 diesel used mud tires for sale cheap girls pantsed and wedgied pics chrysler sebring parts diagram minivan gas mileage comparison chart mens underwear blogspot vinyl siding colors pictures harley davidson parts made in china dvd decrypter download 64 bit poster templates free powerpoint logo creator freeware mac linux mint download mirror jewelry instructions mercedes benz accessories bluetooth wow cataclysm release date rumors jaguar xj 2010 test drive mitsubishi lancer evolution x for sale online rpg space star wars designer wedding dresses with sleeves famous historical hispanic people rolex submariner price used subaru outback gas mileage guitar chords chart printable facebook login proxy chrysler sebring 2008 owners manual compaq mini 110c netbook canon g11 manual pdf hair color trends winter 2010 samsung impression covers pool table dimensions room size civilian contracting jobs overseas portfolio cases for modeling tattoos for guys chest xbox 720 real pictures recipes for chicken breast strips kitchen islands for sale in toronto bathroom corner vanity cabinets youtube full length movies malayalam volkswagen tiguan 2010 diesel summer internships for high school students 2010 samsung solstice a887 black wifi volkswagen jetta for sale by owner gps maps for blackberry 9000 pontiac grand prix for sale in michigan jaguar xf problems radio stations for sale california minivan with best gas mileage toyota sienna parts catalog sturgis biker chicks photos kawasaki ninja 250r mpg golf shoes closeouts volkswagen gti forum play pocket god online game mitsubishi eclipse parts oem flowers for algernon short story summary laptop computer deals walmart dvdfab 6 key siding colors home depot kitchen islands with breakfast bars subwoofer wiring calculator samsung eternity apps glass bongs and pipes for sale laptop computer deals under 400 wireless internet connection keeps dropping pokemon rpgs online best gps systems for truck drivers subaru legacy oem parts open gps tracker android toyota tacoma gas mileage basketball plays motion offense isuzu npr snow summit lift tickets coupons tattoo ideas for men forearm winter olympics 2014


8. Keyboard Interaction (To move the camera)

In this tutorial I'm going to cover keyboard interaction.

(use W,A,S and D)

The very first thing we need to do before we start is to go right back and edit the base class. We're going to make it accept more than one camera, then we can dynamically select the camera, scene and viewport to use.

Open up PaperBase.as (Double click on it in the project tree, under PaperBase). Insert the following lines just below the line "public var default_camera:Camera3D;":

Actionscript:
  1. public var current_scene:Scene3D;
  2. public var current_camera:CameraObject3D;
  3. public var current_viewport:Viewport3D;

These three variables will store the camera, scene and viewport to use in the render. We need to make the default camera, scene and viewport be stored in these variables when we initiate our project, so in the initPapervision function, right at the end, add the following lines:

Actionscript:
  1. current_camera = default_camera;
  2. current_scene = default_scene;
  3. current_viewport = viewport;

The final little edit that we need to make is to render from the current objects.

Change the line "renderer.renderScene(default_scene, default_camera, viewport);" to:

Actionscript:
  1. renderer.renderScene(current_scene, current_camera, current_viewport);

Done. You can download the NEW version of the base class by clicking here!

Now that we've got the base class edited, we can start editing Main.as.

Copy and paste this code into Main.as, make sure you have the papervision library, and the PaperBase class imported in your project's classpaths.

Actionscript:
  1. package {
  2.  
  3.     import PaperBase;
  4.     import flash.events.KeyboardEvent;
  5.     import org.papervision3d.cameras.FreeCamera3D;
  6.     import org.papervision3d.objects.primitives.Plane;
  7.     import org.papervision3d.materials.BitmapFileMaterial;
  8.    
  9.     public class Main extends PaperBase {
  10.        
  11.         public var wdown:Boolean = false;
  12.         public var adown:Boolean = false;
  13.         public var sdown:Boolean = false;
  14.         public var ddown:Boolean = false;
  15.         public var camera:FreeCamera3D;
  16.        
  17.         public function Main() {
  18.             init();
  19.         }
  20.        
  21.         override protected function init3d():void {
  22.             // Initiate 3d
  23.         }
  24.         override protected function processFrame():void {
  25.             // Process Frame Here
  26.         }
  27.     }
  28. }

I've put in all the imports that you'll need for the project. Let's set up the event listeners which will listen for when we press or release a key. Change the code in the Main() function so it looks like this:

Actionscript:
  1. public function Main() {
  2.     init();
  3.     stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
  4.     stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
  5. }

This sets up the two event listeners. Now the functions "onKeyDown" then "onKeyUp" will be triggered when you press a key down, then release it.

If you look at the code, you'll notice that I've declared four boolean values, Wdown, Adown, Sdown and Ddown.

Actionscript:
  1. public var Wdown:Boolean = false;
  2. public var Adown:Boolean = false;
  3. public var Sdown:Boolean = false;
  4. public var Ddown:Boolean = false;

I like to use the W A S and D keys for movement, so each of these boolean values will hold whether W,A,S or D is down.

We'll now set up our onKey functions, which will set the above variables to the correct value. Add this code to your project:

Actionscript:
  1. public function onKeyDown( event:KeyboardEvent ):void {
  2.     // The keycodes for the W,A,S & D keys are:
  3.     // W: 87
  4.     // A: 65
  5.     // S: 83
  6.     // D: 68
  7.     // -------
  8.     switch(event.keyCode) {
  9.         case 87:
  10.             wdown = true;
  11.         break;
  12.         case 65:
  13.             adown = true;
  14.         break;
  15.         case 83:
  16.             sdown = true;
  17.         break;
  18.         case 68:
  19.             ddown = true;
  20.         break;
  21.     }
  22. }
  23.  
  24. public function onKeyUp( event:KeyboardEvent ):void {
  25.         switch(event.keyCode) {
  26.         case 87:
  27.             wdown = false;
  28.         break;
  29.         case 65:
  30.             adown = false;
  31.         break;
  32.         case 83:
  33.             sdown = false;
  34.         break;
  35.         case 68:
  36.             ddown = false;
  37.         break;
  38.     }
  39. }

Pretty simple stuff - Just sets the needed variable to true.

Now we've set that all up, we need to set up our scene. Add the following function to your code:

Actionscript:
  1. override protected function init3d():void {
  2.     camera = new FreeCamera3D(1, 500);
  3.     camera.moveUp(400);
  4.     current_camera = camera;
  5.     for (var x:Number = 0; x <4; x++) {
  6.         for (var y:Number = 0; y <4; y++) {
  7.             var p:Plane = new Plane(new BitmapFileMaterial("http://papervision2.com/wp-content/downloads/concretetex.jpg"), 1000, 1000, 8, 8);
  8.             p.pitch(90);
  9.             p.x = (x * 1000)-2000;
  10.             p.z = (y * 1000)-2000;
  11.             default_scene.addChild(p);
  12.         }
  13.     }
  14. }

Notice that we initiate our "camera" variable here. We then set the current_camera to the camera that we just made. After the line "current_camera = camera", the baseclass will render the scene looking through "camera" instead of "default_camera". The rest of the code in this function just adds a big flat area to the scene which will be our "floor"

Now we can use the boolean variables to move our camera in the processframe function. Add this code to your project:

Actionscript:
  1. override protected function processFrame():void {
  2.     if (wdown) {
  3.         camera.moveForward(60);
  4.     }
  5.     if (sdown) {
  6.         camera.moveBackward(60);
  7.     }
  8.     if (adown) {
  9.         camera.yaw( -8);
  10.     }
  11.     if (ddown) {
  12.         camera.yaw( 8);
  13.     }
  14. }

This just moves the camera forward or back, or rotates it left/right, depending on which key has been pressed.

Your project is now ready to be run. Here is my final code:

Actionscript:
  1. package {
  2.  
  3.     import PaperBase;
  4.     import flash.events.KeyboardEvent;
  5.     import org.papervision3d.cameras.FreeCamera3D;
  6.     import org.papervision3d.objects.primitives.Plane;
  7.     import org.papervision3d.materials.BitmapFileMaterial;
  8.    
  9.     public class Main extends PaperBase {
  10.        
  11.         public var wdown:Boolean = false;
  12.         public var adown:Boolean = false;
  13.         public var sdown:Boolean = false;
  14.         public var ddown:Boolean = false;
  15.         public var camera:FreeCamera3D;
  16.        
  17.         public function Main() {
  18.             init();
  19.             stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
  20.             stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
  21.         }
  22.        
  23.         public function onKeyDown( event:KeyboardEvent ):void {
  24.             // The keycodes for the W,A,S & D keys are:
  25.             // W: 87
  26.             // A: 65
  27.             // S: 83
  28.             // D: 68
  29.             // -------
  30.             switch(event.keyCode) {
  31.                 case 87:
  32.                     wdown = true;
  33.                 break;
  34.                 case 65:
  35.                     adown = true;
  36.                 break;
  37.                 case 83:
  38.                     sdown = true;
  39.                 break;
  40.                 case 68:
  41.                     ddown = true;
  42.                 break;
  43.             }
  44.         }
  45.        
  46.         public function onKeyUp( event:KeyboardEvent ):void {
  47.                 switch(event.keyCode) {
  48.                 case 87:
  49.                     wdown = false;
  50.                 break;
  51.                 case 65:
  52.                     adown = false;
  53.                 break;
  54.                 case 83:
  55.                     sdown = false;
  56.                 break;
  57.                 case 68:
  58.                     ddown = false;
  59.                 break;
  60.             }
  61.         }
  62.        
  63.         override protected function init3d():void {
  64.             camera = new FreeCamera3D(1, 500);
  65.             camera.moveUp(400);
  66.             current_camera = camera;
  67.             for (var x:Number = 0; x <4; x++) {
  68.                 for (var y:Number = 0; y <4; y++) {
  69.                     var p:Plane = new Plane(new BitmapFileMaterial("http://papervision2.com/wp-content/downloads/concretetex.jpg"), 1000, 1000, 8, 8);
  70.                     p.pitch(90);
  71.                     p.x = (x * 1000)-2000;
  72.                     p.z = (y * 1000)-2000;
  73.                     default_scene.addChild(p);
  74.                 }
  75.             }
  76.         }
  77.         override protected function processFrame():void {
  78.             if (wdown) {
  79.                 camera.moveForward(60);
  80.             }
  81.             if (sdown) {
  82.                 camera.moveBackward(60);
  83.             }
  84.             if (adown) {
  85.                 camera.yaw( -8);
  86.             }
  87.             if (ddown) {
  88.                 camera.yaw( 8);
  89.             }
  90.         }
  91.     }
  92. }

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

50 Responses to “8. Keyboard Interaction (To move the camera)”


  • hello, i get this error message when i run your code:

    Error: a target file must be specified

    Use ‘mxmlc -help’ for information about using the command line.
    Build halted with errors (mxmlc).

    what“s the problem? thanx

  • Hi,

    Right click on the project in the Project Tree, click on Properties, then in the output file location box, type the name of the file that you want the project to be output to (I put movement1.swf)

    Thanks, I hope this helps,
    Luke.

  • [QUOTE]

    for (var x:Number = 0; x <4; x++) {
    for (var y:Number = 0; y <4; y++) {

    }
    }
    [/QUOTE]

    Luke, look at the “<” in FORs. :)
    Good example!

    Alek

  • OK thanks, i had already fixed that but forgot to tell. I hadnt checked the “always compile” option of the main.as. that was it, sorry to bother and thanks again

  • Thanks Alek!

    That’s wordpress turning them into html-safe values, I’ll have to fix my syntax highlighter so that it shows them how they should be.

    Luke.

  • hi,

    I’m getting the following error:

    D:\Eigene Dateien\webDesign\PV3d\ConeExample\Main.as(59): col: 4 Error: Zugriff auf eine nicht definierte Eigenschaft current_camera.

    current_camera = camera;
    ^
    If I change current_camera to default_camera I’m getting a type mismatch error!

    thnx

    Stefan

  • “Done. You can download the NEW version of the base class by clicking here!”

    I should have read the whole thing first!

    Replaced my BaseClass and everything runs now!

  • hi,

    you have forget this line for PaperBase:
    import org.papervision3d.core.proto.CameraObject3D;

  • Hello there guys , i just wanted to know if anyone knows how yo achieve the first person shooter effect for the camera. Imean how do you make the camera follow the mouse (having in mind that the camera should rotate and the mouse should stay in the middle).
    Just like in every first person shooter W move forward S move backward A strafe left D strafe right and mouse for Look up down left and right. Also i think that when the camera is looking to the left when you press W it shouldnt look like strafe but move forward should always poin to the direction the camera is aimed at ?
    I will be rly grateful if anyone can explain how this thing happens

  • FWIW: When I adapt this code to a project in Flex Builder, I get a null pointer exception at runtime at this line:

    stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);

    As a workaround, I modified the constructor like so:

    public function Main()
    {
    init();
    this.addEventListener(“addedToStage”, onAddedToStage);
    }

    And added the following function:

    public function onAddedToStage(event:Event):void
    {
    stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
    }

    This works fine, but if anyone has a better solution please share!

  • Are you using Flex 2? I just used with Flex3, no errors…

  • ———————
    Hello there guys , i just wanted to know if anyone knows how yo achieve the first person shooter effect for the camera. Imean how do you make the camera follow the mouse (having in mind that the camera should rotate and the mouse should stay in the middle).
    Just like in every first person shooter W move forward S move backward A strafe left D strafe right and mouse for Look up down left and right. Also i think that when the camera is looking to the left when you press W it shouldnt look like strafe but move forward should always poin to the direction the camera is aimed at ?
    I will be rly grateful if anyone can explain how this thing happens
    ————-________________________

    This lets you move the angle of look

    camera.rotationX = -(viewport.mouseY – stage.height )/1.5 ;
    camera.rotationY = (viewport.mouseX – stage.width )/1.5 ;

    however you need to prevent the mouse from leaving the stage,anyoneknow how to do that?

  • I’m trying this one – I’ve had success with the previous tutorials, but this one has me stumped. I get an error in the Main.as file – line 62:
    col: 36 Error: Type was not found or was not a compile-time constant: InteractiveScene3DEvent.

    Here’s the line.
    private function onPress( e:InteractiveScene3DEvent ):void {

    and then there’s a bunch of errors on the PaperBase code, but I’m guessing they’re occurring as a result of this error?

  • nevermind. I figured it out. I hadn’t added the classpath to Greatwhite.

  • hallo everybody!

    please could you give me a hint – i completed this tutorial and works flawless (thanks Luke!), with only one problem – when i load the flash movie in the html page and reviewing it in browser (no matter of what kind), i have to click the embedded flash to start interaction. usually it has been solved by using the swfobject (2.0) script for implementing the flash movie into the webpage, but it did not help this time. please help!

    be good all, thanx

  • I’ve successfuly went through all of the tutorials, but this one is giving me an
    issue. The problem that I noticed is coming from the the PaperBase.as file that I downloaded and used it for this project. I copied the text from this example and placed it in the Main.as file that I created.

    Here is the code exception error-

    Running process: C:\Documents and Settings\Administrator\Local Settings\Application Data\FlashDevelop\Tools\fdbuild\fdbuild.exe “C:\Documents and Settings\Administrator\My Documents\PaperBase6\PaperBase6.as2proj” -ipc 612563d0-248f-40bf-8a93-15fb544285fd -compiler “C:\Documents and Settings\Administrator\Local Settings\Application Data\FlashDevelop\tools\mtasc” -library “C:\Documents and Settings\Administrator\Local Settings\Application Data\FlashDevelop\Library” -cp “C:\Documents and Settings\Administrator\Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Classes”
    Building PaperBase6
    C:\Documents and Settings\Administrator\My Documents\PaperBase6/PaperBase.as:7: characters 0-7 : parse error Unexpected package
    Build halted with errors (mtasc).
    Done (1)

  • Issue Resolved for both PaperBase.as and Main.as in my project.
    What happened was that my project was created with AS2 not with AS3.
    Applied all the other settings and copied files and pasted code to the Main.as
    and it worked like a charm.

    Thanks Luke for the tutorials and all of you for posting your comments.

  • Small issue here, I think?:)
    I am testing the .swf file and it works in the folder where it was compiled. But when I put the .swf file in another location and view it in flashplayer it show the 3d object but the image is not available.

    Any suggestions welcome.

  • adapted this script and thought I would share the results. This adds a cube which gets moved around by the arrow keys with some friction. A camera then follows behind the cube with some delay so you can see it rotating. Adjust spring and friction vars for different effects

    Hope it helps

    package {

    import PaperBase;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
    import flash.display.MovieClip;
    import flash.text.TextField;
    import org.papervision3d.cameras.FreeCamera3D;
    import org.papervision3d.objects.primitives.Plane;
    import org.papervision3d.objects.primitives.Cube;
    import org.papervision3d.materials.BitmapFileMaterial;
    import org.papervision3d.materials.MovieMaterial;
    import org.papervision3d.materials.utils.MaterialsList;
    import org.papervision3d.lights.PointLight3D;
    import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
    public class Main extends PaperBase {

    public var updown:Boolean=false;
    public var leftdown:Boolean=false;
    public var downdown:Boolean=false;
    public var rightdown:Boolean=false;
    public var camera:FreeCamera3D;
    public var cube:Cube;

    //
    private var xpos:Number=0;

    private var zpos:Number=0;
    private var vx:Number=0;

    private var vz:Number=0;

    private var vxcam:Number=0;

    private var vzcam:Number=0;
    private var spring:Number = 0.1;

    private var friction:Number=.90;
    private var frictioncam:Number=.60;
    private var speed:Number=200;
    private var spacer:Number=800;

    //
    // This is the movieclip that we’ll use as the texture.
    private var movie:MovieClip=new MovieClip;
    private var movieFront:MovieClip=new MovieClip;
    private var movieBack:MovieClip=new MovieClip;

    public function Main() {
    init();
    stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
    trace(‘Use arrow keys’);

    }
    override protected function init3d():void {
    var light:PointLight3D=new PointLight3D(true);
    light.y=400;
    camera=new FreeCamera3D(1,500);
    camera.moveUp(600);
    current_camera=camera;

    var sidemat:FlatShadeMaterial = new FlatShadeMaterial(light, 0xBBBBBB, 0×000000);
    var p:Plane=new Plane(new BitmapFileMaterial(“http://papervision2.com/wp-content/downloads/concretetex.jpg”),20000,20000,50,50);
    p.pitch(90);

    default_scene.addChild(p);

    movie.graphics.beginFill(0xFFFFFF);
    movie.graphics.drawRect(0,0,500,500);
    movie.graphics.endFill();
    movie.graphics.beginFill(0×000000);
    movie.graphics.drawRect(0,0,10,500);
    movie.graphics.drawRect(490,0,10,500);
    movie.graphics.drawRect(0,0,500,10);
    movie.graphics.drawRect(0,490,500,10);
    movie.graphics.endFill();

    var movieFrontText:TextField=new TextField;
    movieFrontText.text=’Front’;
    movieFront.addChild(movieFrontText);

    var movieBackText:TextField=new TextField;
    movieBackText.text=’Back’;
    movieBack.addChild(movieBackText);

    var mat:MovieMaterial=new MovieMaterial(movie,false,true);
    var matFront:MovieMaterial=new MovieMaterial(movieFront,false,true);
    var matBack:MovieMaterial=new MovieMaterial(movieBack,false,true);

    cube=new Cube(new MaterialsList({all:sidemat,front:matFront,back:matBack}),500,500,500,1,1,1);
    cube.y=255;
    default_scene.addChild(cube);
    }
    override protected function processFrame():void {

    var angle:Number=cube.rotationY-180;
    angle=angle * Math.PI / 180;

    if (updown) {

    vx=- speed * Math.sin(angle);
    vz=- speed * Math.cos(angle);
    }
    if (downdown) {
    vx=speed * Math.sin(angle);
    vz=speed * Math.cos(angle);

    }
    if (leftdown) {
    cube.rotationY-= 5;
    }
    if (rightdown) {
    cube.rotationY+= 5;
    }
    xpos+= vx;

    zpos+= vz;

    vx*= friction;

    vz*= friction;

    cube.x=xpos;
    cube.z=zpos;
    var camtargx:Number=cube.x+spacer*Math.sin(angle);
    var camtargz:Number=cube.z+spacer*Math.cos(angle);
    var dx:Number = camtargx – camera.x;
    var dz:Number = camtargz – camera.z;
    var ax:Number = dx * spring;
    var az:Number = dz * spring;
    vxcam += ax;
    vzcam += az;
    vxcam *= frictioncam;
    vzcam *= frictioncam;
    camera.x += vxcam;
    camera.z += vzcam;

    camera.lookAt(cube);
    }
    public function onKeyDown(event:KeyboardEvent):void {

    //trace(angle)
    switch (event.keyCode) {
    case Keyboard.UP :
    //vz += 3;

    updown=true

    ;

    break;
    case Keyboard.DOWN :
    //vz -= 3;

    downdown=true;

    break;
    case Keyboard.LEFT :
    leftdown=true;
    break;
    case Keyboard.RIGHT :
    rightdown=true;
    break;

    default :
    break;
    }
    }
    public function onKeyUp(event:KeyboardEvent):void {
    switch (event.keyCode) {
    case Keyboard.UP :

    updown=false

    ;

    break;
    case Keyboard.DOWN :
    //vz -= 3;

    downdown=false;

    break;
    case Keyboard.LEFT :
    leftdown=false;
    break;
    case Keyboard.RIGHT :
    rightdown=false;
    break;

    default :
    break;
    }
    }
    }
    }

  • I dont know but it does not work for me. I compile the project and run it, but I only have a white screen. Any idea what could be wrong?

  • hi, there
    as I follow all the step from your tutorial from tutorial 1…but and didn’t install papervision1.5 b4 but download papervision 2 directly…
    but i found the Greatwhite folder do not include CameraObject3D and FreeCamera3D there…and the output always tell me these classes are not included…
    would you please tell me what’s the matter…and how to solve these problem? as i have encounter this problem for many times…
    I just start learning papervision…so please understand if this is a stupid question…:P
    btw…your tutorials is do helpful!!!

  • hi there,
    still me…and I have search online…and found this linkage
    http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/cameras/
    where i can find the FreeCamera3D as file…and add it into camera folder…but when i run the program…more file lost there…
    so please suggest some solution for me ba…thx a lot~~

  • hi there,
    btw…i am using flash cs3 IDE PC

  • Hi all,

    I’m using flash CS3 and having difficulty with this particular class. I’ve done everything required and got everything else working up until now. Only difference is that I’m creating a seperate AS3 class called Interactivity which extends the PaperBase class, and then importing that class into my flash file.

    When I run I get the following error:

    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at Interactivity$iinit()
    at interactivity_fla::MainTimeline/interactivity_fla::frame1()

    so there’s a null object in there somewhere, I’ve a feeling it could be in the PaperBase class…

    any suggestions?

  • Hi,

    I’m having the same problem as Evian! Are you using the GreatWhite branch of Papervision! Because mine doesn’t have FreeCamera in the cameras folder.

    If i point my flash to a different version of Papervision, i get even more errors!

    Please can you confirm the version i am meant to use for this tutorial

    Thanks

  • Switching the FreeCamera3D for a Camera3D (import and instances) seems to fix the issue with the missing FreeCamera3D class.

  • How u do that?

    # Comment by Brandon Bradley on July 30, 2008 2:36 am

    Switching the FreeCamera3D for a Camera3D (import and instances) seems to fix the issue with the missing FreeCamera3D class.

  • I had the same problem as Peter. The solution was to switch the FreeCamera3D import and instances to Camera3D along with changing the instiantiation of the Camer3D object.

    Change the following code

    camera = new FreeCamera3D(1, 500);

    to the following

    camera = new Camera3D();
    camera.zoom = 1;
    camera.focus = 500;

  • ok

    camera = new Camera3D();
    camera.zoom = 1;
    camera.focus = 500;

    but there is an empty stage, texture booted that not doing so?

  • And Keyboard Interaction don’t working (((

  • Cool. it’s working)

  • And u must change the PaperBase…

    change the folling code

    default_camera = new FreeCamera3D();

    to the following

    default_camera = new Camera3D();

    and

    // — Cameras –//
    public var default_camera:FreeCamera3D; // A Camera

    to this

    // — Cameras –//
    public var default_camera:Camera3D; // A Camera

  • Hi

    Great tuturials. I am learning a lot here thanks.

    I notice this change I had to make to PaperBase in order to get the following line addition to be accepted at compilation time:

    public var current_camera:CameraObject3D;

    add
    import org.papervision3d.core.proto.CameraObject3D; // CameraObject3D added

  • I keep getting this error:

    Warning: 1090: Migration issue: The onKeyUp event handler is not triggered automatically by Flash Player at run time in ActionScript 3.0. You must first register this handler for the event using addEventListener ( ‘keyUp’, callback_handler).

  • note, with papervision2 you can use DebugCamera3D, which provides the same functionality along with a a textarea containing current display parameters (x,y, fov etc) ..

  • Hi, Im getting this error message:

    …Documents\PaperBase\PaperBase\PaperBase.as(14): col: 35 Error: Definition org.papervision3d.cameras:FreeCamera3D could not be found.

    I’ve double checked it so Im importing all types of cameras in the paperbase.as
    import org.papervision3d.cameras.*;

    and still get this error… any help?

  • Great tutorial, and Goodjob everyone making this works on different versions, i’m learning so much, than you everyone!

  • Thanks for these tutorials too.. great job man~

  • great tutorials (really should get a link at the papervision site), but I’m having a similar problem with the cameras as some others here.
    It’s got me stumped (which isn’t hard, I’m kinda new at this).
    I’m getting an 1120 (it’s finding current_camera to be undefined), but I’m defining it as a CameraObject3D in PaperBase and equating it to the default_camera.
    I’ve checked and rechecked my papervision library (using version 2) and it should have all the necessary resources (has the CameraObject3D in proto and I’ve got my FreeCamera3D in cameras), anyway it’s not giving me any “can’t find the import-errors” so that should be working.

    I’ve been toying with all the different camera-types, but can’t for the life of me see what the problem is (I’m getting so desperate I’ve been checking and rechecking for simple spelling mistakes).

  • Hi, thank you for Great tutorials!!
    By the way,,, recent newer version of GreatWhite(Papervision2.0) seems to quit supporting “FreeCamera3D”.
    That’s why I would see newer version of this example because I still haven’t completely understood about how to use Camera3D class yet.
    Anyway, I really appreciate this great examples you provided for us!!

  • I also see a white screen. I tried using just a plane using colorMaterial but no luck.
    Anybody know whY?

  • For those that got snagged on the missing FreeCamera3D class in Papervision 2.0 like I did:
    If it’s the best way or not, Here is what I used to get it to work.

    Replace this:
    import org.papervision3d.cameras.FreeCamera3D;

    With this:
    import org.papervision3d.cameras.Camera3D;
    import org.papervision3d.cameras.CameraType;
    import org.papervision3d.view.BasicView;

    Replace this in the Main class:
    public var camera:FreeCamera3D;

    With this:
    public var camera:Camera3D;

    And the final change,
    Replace this in the init3d function:
    camera = new FreeCamera3D(1, 500);

    With this:
    camera = new BasicView(800, 600, true, true, CameraType.FREE).cameraAsCamera3D;

    For reference I got the newest API from the docs folder in the downloaded source.
    Hope it helps.

  • Thank you Steve Washuta, your updated code worked like a charm, the first try.

    I tried tinkering around with this on my own (VERY FUTILE).

    Also, for other Flash noobs like me, ‘A’ and ‘S’ will not work when viewing from the Preview mode since A and S are existing Flash hotkeys.

  • Hey Steve Washute, thank you man, your solution really worked out great!

  • Thanks Steve, it works for me but have a strange behaviour. After compilation in flash CS3
    I can only move forward and right. When I open swf file directly everything works fine. Any ideas what is wrong? thanks

  • @Steve,

    Thanks for your update — That’s what solved it after about an hour of head pounding.

    Lawrence

  • i’m using flex builder 3 as compiler and it works. But, I’v got a problem with my own 3D object, i’ve made using Sketchup 7. There was a wire shows around the object and also the material didn’t works properly, it looks mess. Can u help me please?

  • “Also, for other Flash noobs like me, ā€˜A’ and ā€˜S’ will not work when viewing from the Preview mode since A and S are existing Flash hotkeys.”

    You will have to export the movie and not just use the test movie. For some reason it doesn’t report the onKeyDown events for those keys. You can see what keycodes are being read by the script by adding the following to the atKeyDown function:

    trace(event.keyCode);

  • Thanks for the fix Steve W. I was so stumped when I just couldn’t find the FreeCamera3D. :S

    Great tutorial nonetheless.

Leave a Reply


Follow papervision2 on Twitter

Flash and the City banner
2010 Flash And The City Speaker

RSS Feed