7. Basic Mouse Interaction

**Update
This tutorial has been updated:
view-update

In this tutorial, I’ll simply show you how to do some basic movement in the scene by using the mouse.

This is the result:

Ugly, but simple. It’s so simple that I’m just going to post the source code.. If you’ve been following my last tutorials, and you read the comments around the three lines of code in “ProcessFrame” then you should understand it.

package {
 
    import PaperBase;
    import org.papervision3d.objects.DisplayObject3D;
    import org.papervision3d.objects.parsers.Collada;
 
    public class Main extends PaperBase {
 
        public var cow:DisplayObject3D;
        public var distance:Number = 1000; //Distance the camera should be from the model
 
        public function Main() {
            init();
        }
 
        override protected function init3d():void {
            cow = new Collada("http://papervision2.com/wp-content/downloads/dae/cow.dae");
            cow.moveDown(100);
            cow.scale = 3;
            default_scene.addChild(cow);
        }
        override protected function processFrame():void {
            // The next line is a bit of a mouthful, but it's quite simple really.
            // It just gets the Y position of your mouse, and sets the camera.y to a
            // value between -800 and 800, depending on the Y position of your mouse
            // (If mouseY = 0 then camera.y = 800. If mouseY = stage.height, camera.y = -800)
            default_camera.y = -(((mouseY - (stage.height / 2)) / stage.height) * 1600);
 
            // We don't want the camera to move further away from the model, so we do this:
            default_camera.moveForward(default_camera.distanceTo(cow) - distance);
 
            // We now want to rotate the object depending on
            // the Xmouse position. This is really simple.
            cow.rotationY = -((mouseX / stage.width) * 360) //Rotation
 
            // NOTE: This will only work if you only have one object in your scene.
            // I'll write a more advanced movement tutorial soon :)
        }
    }
}

If you’re seeing just white space because you’re using the Flash IDE please use this as your final code:

package 
{
	import PaperBase;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.parsers.Collada;
 
	public class Main extends PaperBase 
	{
		public var cow:DisplayObject3D;
		public var distance:Number = 1000; //Distance the camera should be from the model
		protected var sceneWidth:Number;
		protected var sceneHeight:Number;
 
		public function Main() 
		{
			sceneWidth = stage.stageWidth
			sceneHeight = stage.stageHeight;
			init(sceneWidth,sceneHeight);
		}
		override protected function init3d():void 
		{
			cow = new Collada("http://papervision2.com/wp-content/downloads/dae/cow.dae");
			cow.moveDown(300);
			cow.scale = 2;
			default_scene.addChild(cow);
		}
		override protected function processFrame():void {
 
			// The next line is a bit of a mouthful, but it's quite simple really.
			// It just gets the Y position of your mouse, and sets the camera.y to a
			// value between -800 and 800, depending on the Y position of your mouse
			// (If mouseY = 0 then camera.y = 800. If mouseY = stage.height, camera.y = -800)
			default_camera.y = -(((mouseY - (sceneWidth / 2)) / sceneHeight) * 1600);
			// We don't want the camera to move further away from the model, so we do this:
			default_camera.moveForward(default_camera.distanceTo(cow) - distance);
			// We now want to rotate the object depending on
			// the Xmouse position. This is really simple.
			cow.rotationY = -((mouseX / sceneWidth) * 360) //Rotation
			// NOTE: This will only work if you only have one object in your scene.
			// I'll write a more advanced movement tutorial soon
		}
	}
}

**EDITED**

2 sets of code for this one. If you’re using the Flash IDE please use the 2nd version.

This entry was posted in Tutorials. Bookmark the permalink.

41 Responses to 7. Basic Mouse Interaction

  1. Alek says:

    Luke I see a white screen, there is something that I’m missing?
    Thank you very much! I’m following your blog, it is so helpfull.

    Alek

  2. Mike says:

    Hi,

    I changed it to fit for Flash CS3, as well:

    package {

    import base.PaperBase;
    import org.papervision3d.objects.DisplayObject3D;
    import org.papervision3d.objects.parsers.Collada;

    public class CowExample extends PaperBase {

    public var cow:DisplayObject3D;
    public var distance:Number = 1000; //Distance the camera should be from the model
    public var $currentRoot;

    public function Main($root) {
    this.$currentRoot = $root;
    init($root);
    }

    override protected function init3d():void {
    cow = new Collada(“http://papervision2.com/wp-content/downloads/dae/cow.dae”);
    cow.moveDown(100);
    cow.scale = 3;
    cow.pitch(-30);
    default_scene.addChild(cow);
    }

    override protected function processFrame():void
    {

    // The next line is a bit of a mouthful, but it’s quite simple really.
    // It just gets the Y position of your mouse, and sets the camera.y to a
    // value between -800 and 800, depending on the Y position of your mouse
    // (If mouseY = 0 then camera.y = 800. If mouseY = stage.height, camera.y = -800)
    default_camera.y = -(((this.$currentRoot.mouseY – (this.$currentRoot.height / 2)) / this.$currentRoot.height) * 1600);
    // We don’t want the camera to move further away from the model, so we do this:
    default_camera.moveForward(default_camera.distanceTo(cow) – distance);
    // We now want to rotate the object depending on
    // the Xmouse position. This is really simple.
    cow.rotationY = -((this.$currentRoot.mouseX / this.$currentRoot.width) * 360) //Rotation
    // NOTE: This will only work if you only have one object in your scene.
    // I’ll write a more advanced movement tutorial soon :)
    }

    }

    }

    Mike

  3. Manuel says:

    I have a white screen, too. The same as in tutorial 6. Can you explain what I have to write in my code when I have downloaded the model and texure files?
    I`m an absolutely noob ;)
    Sorry for my English. I`m from Germany

    Manuel

  4. Asmodeus says:

    Hi Luke,

    like Alek and Manuel i also have a whit screen :/ Why is that ? Did i miss some configurations steps ?

  5. minipower says:

    Hi to all! i am NOT a programmer or someone important, i am minipower but…in the first tryout i had white screen like others then.. i resolved copying the plain text code version and in flashdevelop it worked fine!!!

    Maybe some kind of error writing comments or other :)

  6. Robin says:

    I have a white screen too, but only if the dimensions are less then 800×600…

  7. Ramiro Araujo says:

    Im getting a blank screen too, but if I test again with Ctrl + enter (simulates download) it gets it right. Im sure its not a code problem. Will probably work ok online.

  8. Juan says:

    Hi, I have found a solution for CS3

    package {
    import PaperBase;
    import org.papervision3d.objects.DisplayObject3D;
    import org.papervision3d.objects.parsers.Collada;

    public class Main extends PaperBase {
    public var cow:DisplayObject3D;
    public var distance:Number = 1000;

    public function Main() {
    init();
    }

    override protected function init3d():void {
    cow = new Collada(“http://papervision2.com/wp-content/downloads/dae/cow.dae”);
    cow.moveDown(100);
    cow.scale = 3;
    cow.pitch(-30);
    default_scene.addChild(cow);
    }
    override protected function processFrame():void {
    default_camera.y = -(((this.mouseY – (this.stage.stageHeight / 2)) / this.stage.stageHeight) * 1600);
    default_camera.moveForward(default_camera.distanceTo(cow) – distance);
    cow.rotationY = -((this.mouseX/this.stage.stageWidth)*360) //Rotation
    }
    }
    }

    the stage width and height in Flash CS3 is get by this.stage.stageWidth and this.stage.stageHeight

  9. Matt m says:

    That works in flex 3, also:

    change all stage.height to stage.stageHeight and stage.width to stage.stageWidth

  10. webmaster says:

    Yes It does work in Flex 3…
    probably simple question: is the reason the cow is at the lower right of the screen always because of the coordinates in the orignal .dae file?

  11. kea says:

    First, I would like to thank you for this great work ! Papervision and flashdevelop look like great tools, but they definitely lack good tutorials. I can’t tell you how grateful I am…
    However, I feel realy stupid, as I am stuck with a problem I can’t solve. It is probably simple, but I have to admit I am completely lost.
    Everything is working fine with the tutorials. I’ve adapted this one to my object (a simple cube, instead of the cow…) When I test it, it does work fine (yeah ! I’m in 3D ! Awesome !)
    Unfortunately, my ultimate goal is to put it on a website. Problem is : as soon as I move my swf file (on another folder or on my server), it doesn’t work anymore.
    Even if I move also the .dae, the texture, the .as files and the obj folder. Even when I change all paths (relative or absolute, even in the XML file…what is this one for, anyway ?)
    I’ve been trying for a few hours now, but no luck. I think I’m gona cry !
    So in short : what files will I need to upload on my server ? And do you know how to solve what seems to be a path problem ?

    Thank you again for the good work, anyway. :-)

  12. Hokusai_spain says:

    Kea, maybe your problem is the sandbox security model. A explains about sandbox: work.whoischarles.com/files/flash_player_9_security_model.pdf

  13. cih says:

    Thank you for the great tutorials, we are expecting more : )

    a question: I have a project where the user can create a painting and then attach the painting to the 3D model as a texture. I can update the texture png while the swf is still running, but cannot update the texture on the model. Removing and adding “cow” child does not update the texture. How can I remove the “cow var” totally to be able to add later?

    Thanks a lot!

  14. Pingback: Demo 080526 ~ 3D 球體 « Markvann + ActionScript

  15. jasonw says:

    My cow doesn’t stay locked to the center of the screen when I move my mouse vertically. The cow moves up and down vertically. The rotation works fine, I just can’t figure out why the cow won’t stay centered when I move my mouse along the Y axis.

    Any ideas?

  16. Pingback: Peter Pawan’s Blog » 3D in Flash. First steps.

  17. Jay says:

    @jasonw:

    Probably the codebase has changed.
    Using camera.lookAt( cow ) inside the processFrame() method fixes it for me.

  18. Pingback: Hebi Flash Blog » 9 navigations pour la 3D sur le web… et plus ?

  19. Fraanske says:

    Great tut, but I’d like to know some less basic techniques. With Great White out in the water, we get a whole set of new goodies such as shaders, but mouse interaction has become a bit more difficult. The only tut that gives me 100% what I need, is horribly complex (as in “too time consuming to deploy quickly”). I’d like to know a technique that was more like 1.7, when you could attach filters and EventHandlers to a 3DObject’s internal container sprite. I’d like to know how to set EventHandlers on objects directly, instead of handling MouseEvents on the Stage. Still, I like your tut to display a single object: it’s perfect for that purpose!

  20. breeze79 says:

    default_camera.moveForward(default_camera.distanceTo(cow) – distance);
    cow.rotationY = -((mouseX / stage.width) * 360) //Rotation

    I too get the white screen. However, if you comment those two lines you can see the cow and it will move up and down.
    I don’t know why the lines above gives white screen.. maybe something with the calculation???

  21. atadami says:

    i’m getting a blank white screen too. even on this tutorial page at the top the example is blank.

  22. cnew says:

    Make sure that you don’t have the yaw going or you end up with the white screen.

  23. shady says:

    在flash CS3里,场景宽高应该用this.stage.stageWidth及this.stage.stageHeight获取,这个跟flex是不同的~

  24. Bell says:

    Hi luke,
    Thanks a lot for these tutorials. They really help me get into PV3D more.
    Now I am trying other interations like clicking mouse on collada objects.
    But I suffered some problems…can i ask this question here?
    I added these lines in the code of this example:

    import org.papervision3d.events.InteractiveScene3DEvent;
    [...]
    cow.addEventListener( InteractiveScene3DEvent.OBJECT_PRESS, onPress );
    [...]
    private function onPress( e:InteractiveScene3DEvent ):void { trace(“clicked!”); }

    The PaperBase.as has been updated to the newest one.
    I got no error during compile and runtime, but neither any responses when i clicked the cow.
    Should I turn on the property of interactive options like [ourMaterial.interactive = true;]?
    Now I can do OBJECT_PRESS on plane and cube object well, but how does that work on collada?
    thx for reading.

  25. Rain says:

    Hello!

    I have a question: How do i publish the swf file in other place?

    Now i can view it at local machine.

    If i change the files place, i can’t see the 3D object.

    THX!

  26. Greg says:

    Yeah, I see blank screen too.. I think it’s probably some kind of FlashPlayer issue. After update to 10 version this SWF doesn’t work properly.

  27. Evio says:

    Change publish settings to Flash Player 9.
    On flash player 10 it doesn’t work.

  28. Strider says:

    I don’t Know if it comes in handy to anyone, But i too get Blank screens in all tutorials, when The FlashDevelop export them, and also when I run the SWF file on a Window, but if a Open the .SWF file using Firefox, everything is just fine.

  29. LUCAS HUANG says:

    hi Everybody:

    I find two statements that will nothing happen.

    //nothing happen
    public var distance:Number = 1000;
    //nothing happen
    default_camera.moveForward(default_camera.distanceTo(cow) – distance);

    Somebody can tell me why?
    If i delete these , I can get the same swf.Nothing different.
    And i can’t find “moveForward” in the Camera3D class.

  30. LUCAS HUANG says:

    Hi
    Somebody told their cow are not center on the swf.
    I think it is because
    PaerBase.as
    public function init(vpWidth:Number = 800, vpHeight:Number = 600)…..

    If your fla are not 800*600, the cow will not center.

    Sorry to my English.

  31. jaziel says:

    this code is somehow broken. it’s not working.

  32. Charlie says:

    Hey Jaziel,

    The code should not be broken. I just personally ran a test from scratch. Please ensure you’re using the latest papervision classes.

    You can download them from SVN here:
    http://code.google.com/p/papervision3d/source/checkout

    or I went ahead and compiled a zip of the latest for you:
    http://papervision2.com/download/papervision/papervision-classes.zip

    Please also make sure that you’re using the latest paperbase class found here:
    http://papervision2.com/PaperBase.as

  33. jaziel says:

    thanks for the reply. took me the whole night to figure out what’s wrong.

    since I’m building it with flex.

    just 30 seconds ago. when I execute the .swf files instead of launching the HTML on IE7 it worked. I didn’t change anything but it worked.

    My guess was just either IE7 was not in the mood last night or the Sever’s been slow.

  34. nestos says:

    distanceTo() is defined in the DisplayObject3D class

    but there is still something to fix in this movement

    antyway, great tutos here !

  35. adam says:

    please put the following line at the beginning of function processFrame:

    if (stage.width <= 0 || stage.height <= 0) {
    return;
    }

    When this function is called before initialization, cow and camera posstion will be a NaN, causing a white screen.

  36. zach says:

    Is there a way just to have the code and replace the collada files? just to switch objects faster. i know of coarse you’ll have to change the code a little replacing “cow” with whatever. but is there that possibility?
    zach@fivestonestudios.com

  37. Neogine says:

    thanks it’s working perfectly

  38. Pingback: Blagoratory » Blog Archive » “Hip to be Square?” Building a Rotating Video Cube in Papervision 3D.

  39. Peter says:

    man im noob why is it extending PaperBase and not BasicView i have coded already in basicView. do i have to change?

  40. Charlie says:

    @Peter – this tutorial has been updated to extend BasicView. I left old tutorials in case someone wanted to reference them later.
    Here is the updated tutorial:
    http://papervision2.com/basic-mouse-interaction-v2/

  41. Gonzo says:

    Hi…
    I generate 4 planes and their materials with a for cycle (from …but when I click on them their name are starting from 6 to 9 instead of 1-4…why?
    here’s the code:
    //// start
    var menuItems:Number=4
    var menuLabels:Array=new Array(‘Abcd’,'Abcdacbd’, ‘Accabcab’, ‘abc’)
    for (var i:Number=1;i<menuItems+1;i++){

    root['my_menuItem'+i].title_mc.title_txt.text=menuLabels[i-1]
    root['menuItem_material'+i]=new MovieMaterial(root['my_menuItem'+i],true);
    root['menuItem_material'+i].interactive=true;

    root['menuItem_material'+i].movieTransparent = true;
    root['menuItem_material'+i].animated = true;
    root['menuItem_material'+i].smooth = true;
    root['menuItem_material'+i].precise = true;
    root['menuItem_plane'+i]=new Plane(root['menuItem_material'+i],250,50,34+i,35+i);

    root['menuItem_plane'+i].x=500
    root['menuItem_plane'+i].y=-50-(60*i)
    root['menuItem_plane'+i].z=-100
    trace ('plane '+root['menuItem_plane'+i])

    root['menuItem_plane'+i].addEventListener(InteractiveScene3DEvent.OBJECT_CLICK,on_item_clicked);

    scene.addChild(root['menuItem_plane'+i]);
    ///

    }
    //// end
    the output it's
    plane 6: x:500 y:-110 z:-100
    plane 7: x:500 y:-170 z:-100
    plane 8: x:500 y:-230 z:-100
    plane 9: x:500 y:-290 z:-100

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">