Home  >  

Papervision3D Movement- Going Where No MovieClip Has Gone Before

Author photo
| | Comments (14)
AddThis Social Bookmark Button
Changing Position- Move that 3D Thing!

If you’re anything like me, you remember how excited you were years ago when you first wrote a simple line of code, ball._x++, in an onEnterFrame event and gleefully watched a ball fly across the stage. I promise you that little moving ball ain’t got nothin’ on what you’re about to learn here.

Properties: x, y, and z

You position an object in 3d space by plotting out its x, y, and z coordinates. Now it only makes sense, just like that ball moving across the stage years ago, that incrementing an x, y, or z value in Papervision3D using an ENTER_FRAME event will achieve the same purpose. Yet, there are a few gotchas:

  • x:0, y:0, and z:0 is the center of the stage(unlike a traditional flash stage with x:0 and y:0 in the upper-left corner)
  • y++ moves up
  • z++ moves forward

Every DisplayObject3D uses these x, y, and z properties and you can access them directly on the object:


myCube.x++; //moves myCube right one pixel

You don’t typically directly increment the position values of a 3d object as there are methods and Tweening engines that simplify movement in 3d space

Click to Demo
Click on Preview Above to Run Demo.

Methods: moveForward(), moveBackward(), moveLeft(), moveRight(), moveUp(), and moveDown() I’ll give you one guess to figure out what “moveForward()” does to a 3d object. Give up? “moveForward()” moves the 3d object forward. Unlike a z++, moveForward() takes rotation into account. This means your object will move forward no matter what direction it faces. Let’s imagine two diametric examples to make sure we’re clear:

  • Going down can be moving forward: Imagine an airplane in a nose-dive. Even though you could say the plane is going down, the rotation of the plane has changed in such a manner that the pilot would say, “We are moving forward towards the ground.”
  • Going forward can be moving down: Imagine a motorcycle popping a perfect wheelie. The motorcycle would be pointed toward the sky, but you would have to define his motion as “moveDown()” because it’s turned so far back on its back wheel that the bottom is moving forward.

So it all boils down to this: if you want to move a sphere named “sphere” 10 pixels forward:


sphere.moveForward(10);// moves a sphere forward 10 pixels

If you want the sphere to continue to move forward, place the preceding line of code within an ENTER_FRAME event handler.

Adjusting Scale- Because Bigger is Always Better

Properties: scale, scaleX, scaleY, and scaleZ

There’s one underlying rule in life that we all have to deal with on a daily basis: size matters.

In 3d space, the only way to visually determine the size of an object is to compare it to another nearby object. If you’re new to manipulating 3d space, you’ll run into this problem often because you have to take the size of your 3d object and all of the camera properties into account.

If you need to adjust the size of the object compared to other objects and you like where the object is positioned, the easiest method is to play with its scale settings.

  • scaleX - stretches/shrinks the object along the X-axis or left and right
  • scaleY- stretches/shrinks the object along the Y-axis or up and down
  • scaleZ - stretches/shrinks the object along the Z-axis or front and back
  • scale - strecthes/shrinks the object equally on all axes (that’s plural for more than one axis)

The following example demonstrates scaling in 3D:

Click to Demo
Click on Preview Above to Run Demo.

Simple Rotations*- You Spin Me Right Round, Baby, Right Round

*author’s note: This section is subject to change in future revisions based on current internal discussions within the Papervision3D team

Properties: rotationX, rotationY, rotationZ, localRotationX, localRotationY, and localRotationZ

Methods: pitch(), yaw(), and roll() In Flash, whenever you rotate a MovieClip it only rolls right or left, similar to the hands turning on a clock. Papervision3D adds two new ways to rotate. The one you’re familiar with, turning clockwise or counter-clockwise, is known as rolling, or rotationZ because the object is rotating around the Z-axis. You can think of the Z-axis as you and friend facing each other holding long axle with a wheel at the middle. Turning the axle in your hands would make the wheel roll. So the axle is the Z-axis and turning an object on the Z-axis makes it roll.

Yaw (rotationY) and pitch (rotationX) might be new to you, but the concepts are just as simple. For instance, the earth spins on its Y-axis as do figure skaters, tornadoes, and those toy tops you used to play with as a kid. If you need to hold a Y-axis to grasp the concept, just grab your nearest spindle of burnable CDs and start spinning your CDs around it. That plastic rod jotting up out of the base is a good example of a Y-axis and the CD spinning around the Y-axis an example of yaw or rotationY. Simple, right?

Last, but not least, is the pitch or rotationX. Get up out of your chair and do a somersault. Assuming you were successful, you’ve completed a 360 degree pitch because you rotated around the X-axis. If you just got in trouble by your boss for doing somersaults in the office, just tell him you’re doing research and do another one.

Now that you understand the concept, let’s talk about how and why to use each variation:

rotationX, rotationY, and rotationZ

Consider these three properties as “object axis rotation”. Most commonly you set the rotation once then forget about it. Think of a space shuttle. The space shuttle, while in Earth’s atmosphere, flies like any other airplane: horizontally. Yet, when it’s time to lift off into outer space, the space shuttle flies vertically. In this situation, you would adjust the rotationX 90 degrees and then forget about it. So consider these rotations as a way to orient your object to the direction you’d like it to face.

localRotationX (pitch), localRotationY (yaw), localRotationZ(roll)

These local rotations will now rotate around the object axis. So once you orient your object with the base rotations, you can now rotate around the new orientation with the local rotations. (Take note that the method pitch(), yaw(), and roll() achieve the exact same functionality as these local rotation properties. They take a degrees parameter and will update the local rotation by that many degrees). A local rotation also does the following things which you’ll need to remember:

  1. 1. Updates incrementally. Each local rotation builds upon the prior local rotation. Although this is correct, you will most likely not get the results you expect. Adding 3D rotations is much more complicated than you may initially assume.
  2. 2. Modifies the orientation rotation. This may seem counter-intuitive, but must be done to maintain proper moveForward(), moveRight(), etc. functionality.

Lastly, setting a rotationX after setting a localRotationX will reset all of the local rotations. This means the object will return to the orientation rotation defined in rotationX, rotationY, and rotationZ. This, in effect, cancels out the changes made to the orientation by the local rotations.

The following example demonstrates the points made above. The sliders adjust the orient rotations while the buttons do a 360 rotation around a local rotation. The demo pretty clearly shows the difficulty in combining multiple rotations at the same time:

Click to Demo
Click on Preview Above to Run Demo.

Controlled Rotations- lookAt()

Methods: lookAt()

You probably gathered from the “Simple Rotations” section that combining 3D rotations can get complicated quite quickly. If you want to delve into the math behind 3D rotations and solutions you can use to control them mathematically, read up on the following topics:

On the other hand, if you’re looking for a simpler solution, read on.

The lookAt() method is available on every DisplayObject3D (sphere, plane, cube, etc.). It allows you take make one object look at another. The syntax is very simple:


plane.lookAt(sphere); //results in the plane looking at the sphere

Now you may be thinking, “I see what this does, but how does it help control rotations?” The answer is that you can now position dummy objects around the scene using x,y, and z and then lookAt() those objects to create the desired rotation of the main object. If you want to rotate something to the upper left, place an object up and to the left then look at it. The following example demonstrates an arrow looking at different spheres:

Click to Demo
Click on Preview Above to Run Demo.

If you don’t want the object you’re looking at to be seen, don’t add it to the scene.

Orbiting with Pivot Points

Pivot Points allow you to group a whole bunch of 3d object together at different positions and rotate them around one axis. It’s similar to how all the planets in the solar system rotate around the Sun. The basic usage of a Pivot Point is very simple, yet it can yield pretty cool results. Create a couple objects, create a Pivot Point (just a basic DisplayObject3D), add the objects to the Pivot Point, then add the Pivot Point to the scene:


var sphere1:Sphere = new Sphere();
var sphere2:Sphere = new Sphere();
var pivotPoint:DisplayObject3D = new DisplayObject3D();
//add your objects to the pivot point
pivotPoint.addChild(sphere1);
pivotPoint.addChild(sphere2);
//add your pivot point to the scene
scene.addChild(pivotPoint);

After this is all said and done, you can rotate the Pivot Point using the methods discussed above and the objects you placed within the Pivot Point will all rotate together. Check out the following example to get the idea:

Click to Demo
Click on Preview Above to Run Demo.

Tweening in 3D with TweenMax

There are many open source options for making things move in Flash. I’ve decided to use an engine called TweenMax because it’s a solid, fast engine that’s easy to learn in an online article. Follow this link and click the big green “Download Now” button toward the top of the page:

http://blog.greensock.com/tweenmaxas3/

Extract the .zip to wherever you keep your classes and set a class path to import TweenMax. A typical syntax is short sweet and simple (yet has limitless options):


TweenMax.to(myObject, duration, {myProperty:endResult});

You can play around with the tween customizer on the TweenMax homepage to generate some more examples. Make sure and check out the easing methods from the code generator to smooth out your transitions. After playing with the code generator, try swapping in any 3d object and 3d property into the static to() method:


TweenMax.to(sphere, 2, {z:1000});//Tweens a sphere from its current z location to z 1000

Go ahead and try out each property we’ve looked at. You can even try tweening multiple properties simultaneously. You’ll quickly see how easy it is. Let’s combine some of the ideas we’ve learned for the final demo.

Click to Demo
Click on Preview Above to Run Demo.

The preceding example can be thought of like this:

  1. 1. Tween a dummy object to the x, y, and z of a sphere
  2. 2. Update the arrow object to lookAt() the dummy object for proper rotation
  3. 3. Update the arrow object’s x, y, and z to follow the dummy object through 3d space

The nifty little curving effect comes from an option called “bezierThrough” provided by TweenMax. The syntax looks like this:


TweenMax.to(dummyArrow, 2, {x:sphere.x, y:sphere.y, z:sphere.z, bezierThrough:[{x:1000, y:1000}], onUpdate:updateArrow, ease:Quart.easeInOut});//Tweens a dummy object to a sphere with a bezier of x:1000 and y:1000. Also calls updateArrow() each time the tween updates

The updateArrow function should look something like this:


private function updateArrow():void
{
 //gives a little lag between the arrow for smoother rotating
 dummyArrow.moveBackward(200);
 //arrow looks at dummy arrow
 arrow.lookAt(dummyArrow);
 // arrow copies the x, y, and z of the dummyArrow
      arrow.copyPosition(dummyArrow);
}

There are truly limitless possibilities of movement in 3D. If the movement happens around you in everyday life, you can bet there’s some way to achieve that same movement effect in Papervision3D. So let your imagination run wild and make cool stuff!

Read more from John Lindquist. John Lindquist's Atom feed

Comments

14 Comments

lr said:

Great article! Would you mind to share the project code please? or is there any link to download the files?
Cheers

I'll pack up the code into flex archives in the next week or so and post a link in the comments.

Shawny said:

Great post. I love the look-at method. I would think that having mouse-oriented object that can be aware of other internal objects could be quite useful.

Anonymous said:

Thanks, John! :)

felix said:

Is there any way to add "enter_frame" listeners to 3d objects?

Chin-Chi Hung said:

Great artical! If have any chances to teach how to put Flex 2D UI (like HTML, Panel...) into PV3D environment. Thanks.

haha said:

Thanks!

Antoy said:

Great article, thanks John! Is possible to have the project code please?

stelios said:

Very useful article. Thanks. Unfortunaterly I can't understand it very well because you haven't packed the complete source code. I hope you will do it in the future.

Claudio said:

Hey guys, everybody is asking for the source code here.. Well I can understand you would like to have it but I feel you are asking too much this time.. These examples are well structured and well explained, and the idea of these post is to let us understand the basics, then it's our job...

your wrong said:

@Claudio your wrong, code or GTFO

David said:

Very interesting. Would be very helpful if the promised zipped code could be available (I'm writing this about eight months after the last person requested!).

Marek Mis said:

Thank You! The best explanation of PV3D for begginers. Cheers!

Leave a comment


Tag Cloud

Question of the Week: Open Source Flex Projects

What would you say are the 5 most prominent open source projects in the Flex world?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.