I’ve made a couple of small improvements to the PaperSprite class:
- The visible face of the plane is updated automatically only when required. This saves on processing load and also means you can just set up the PaperSprite and not have to worry about anything else, just tween the crap out of all its properties and it won’t mind one bit. (Thanks to Jesse for the pointers re. using stage.invalidate for this process)
- The back face is now automatically flipped horizontally, so text and graphics are no longer mirrored and will display correctly
- I’ve changed the logic which sets the dynamic registration point for the pivot. This should now correctly line up the front and back faces of the 3D plane, regardless of where their individual registration points are.
Also, some people have asked how to use it, so here is a really quick example to get you up and running with PaperSprite if you are not familiar with using classes and are using the Flash IDE to compile your movie:
- First, download the PaperSprite class and put the soulwire folder in the same directory as your FLA or source code.
- Then paste this code into the main timeline of your FLA:
// Import the PaperSprite class
import soulwire.display.PaperSprite;
/*
Create a new PaperSprite:
If your front and back faces already exist, you can pass them straight
into the constructor, like so:
myPaperSprite = new PaperSprite( myFrontMc, myBackMc );
*/
var myPaperSprite:PaperSprite = new PaperSprite();
/*
Optionally specify a pivot point, in this example the centre is used
(this is also the default so there is no need to set this normally).
To pivot around the top left use:
myPaperSprite.pivot = new Point(0,0);
or for bottom right:
myPaperSprite.pivot = new Point(1,1);
and so on...
*/
myPaperSprite.pivot = new Point(0.5,0.5);
// Centre it on the stage
myPaperSprite.x = stage.stageWidth / 2;
myPaperSprite.y = stage.stageHeight / 2;
/*
Set the front and back faces:
These can be any type of DisplayObject, for example, to use a MovieClip
from your library use:
myPaperSprite.front = new MyLibraryClip();
*/
myPaperSprite.front = createSprite(0x66FF00);
myPaperSprite.back = createSprite(0xFF3399);
// Add the PaperSprite to the display list
addChild ( myPaperSprite );
// This method just creates coloured boxes for the demo
function createSprite (colour:uint):Sprite
{
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill ( colour );
mySprite.graphics.drawRect (0,0,100,100);
mySprite.graphics.endFill ();
return mySprite;
}
// Listen for the enterFrame event
addEventListener ( Event.ENTER_FRAME, spin );
/*
Move and rotate your PaperSprite in any way you want - it will
update it's visible face automatically!
*/
function spin ( event:Event ):void
{
var mX:Number = ((mouseX / stage.stageWidth) - 0.5) * 360;
var mY:Number = ((mouseY / stage.stageHeight) - 0.5) * 360;
myPaperSprite.rotationY += (mX - myPaperSprite.rotationY) / 40;
myPaperSprite.rotationX += (mY - myPaperSprite.rotationX) / 40;
}
Publish the movie and you’re all done!
Background
Flash Player 10’s new 3D capabilities are a much welcomed and exiting addition, and although their implementation at first seemed a little obtuse after using libraries such as Papervision3D, Adobe’s implementation is beginning to make a lot more sense to me. Rather than being handed a complete 3D library, developer’s have been given the necessary building blocks to use 3D, or 2.5D with less ‘hacks’ and arguably better performance where it matters.
Time will tell, but I personally think this will be a positive development for existing frameworks like Papervision and Sandy, because whilst Flash can now natively handle certain tasks like triangle drawing, 3D matrices etc – implementing cameras and shaders, loading and building meshes and so on is something which developers will still require. If this can plug neatly into Flash Player’s capabilities and possibly yield increased performance then all the better.
In more basic situations though, the ability to rotate a DisplayObject around its X, Y and Z axis, as well as finally having a Z property, is useful for adding basic 3D effects, even if your project doesn’t require anything more sophisticated than that.
But this is where some gaps begin to arise. Z sorting, for example, will be required, and Ralph Hauwert (a member of the Papervision3D team) has already written a useful script for this.
Two Sided DisplayObjects
Another common use for Flash Player 10’s 3D capabilities is to create double sided sprites or planes, than can be rotated to reveal alternate content on either side. Again, I would have expected this to be a new property of DisplayObjectContainer, so that front and back could be passed to it as DisplayObjects. This isn’t the case though, so it requires some minimal work around.
Lee Brimelow demonstrated one approach to this, which was to monitor the rotation of a DisplayObject, and swap the visible faces accordingly (Jesse Freeman also used this technique). This works great in many cases, however it doesn’t give the desired results when the parent DisplayObject is off centre and therefore subject to the perspective of the 3D environment. It also means that if you are rotating the DisplayObject around multiple axis then the calculations required get slightly more complex.
The Solution
As ever, the wise and prolific Senocular came to the rescue. He described a technique whereby 3 points are placed on the surface of the DisplayObject, and by determining the winding direction of these points when translated from 3D to 2D space; one is able to determine which way the DisplayObject is facing. Because this is relative to the perspective used to produce this transformation, the result is true to the point of view of the user.
Senocular published his helper class which will return a Boolean value indicating whether a given DisplayObject is front facing or not, and so I wish to stress that all credit is his for his solution and wonderfully clear explanation of the process.
I did feel that it might be beneficial though to wrap this up, along with other functionality, into a class which solved the double sided DisplayObject issue, and so I introduce the PaperSprite class (I chose to call it PaperSprite so that it isn’t confused with Sprite3D if you use another 3D library).
How to use PaperSprite
Creating a two sided Plane using PaperSprite is simple:
import soulwire.display.PaperSprite;
var mySprite:PaperSprite = new PaperSprite();
// Any type of DisplayObject can be used for each face
mySprite.front = new Sprite();
mySprite.back = new Bitmap( myImage );
So you can use any DisplayObject for the front and reverse sides; MovieClips, Sprites, Bitmaps, Shapes, Loaders etc. These can also be set via the constructor…
Another property of PaperSprite is whether is updates it’s display automatically. If true, once the PaperSprite is added to the stage it will update its visible face autonomously, however if you have a more general render loop where you’re controlling your 3D scene from, you can set this to false and then call the update method when calculating the visible face is required:
Thanks to Jesse Freeman for suggesting a method to limit unnecessary calls to the update method. By overriding the setters for the position and rotation properties and using stage.invalidate(), then listening for the render event (Event.RENDER), the calculations needed to determine the visible face of the PaperSprite need only be made if one or more properties have been changed and if the PaperSprite needs to be rendered. Therefore there is no longer a need for autoUpdate, everything is handled internally by the PaperSprite class. Cheers Jesse! :)
…The other useful feature is the pivot property. By default, a PaperSprite will pivot (rotate around) its centre point, which will be automatically calculated for each face depending on its respective dimensions. Alternatively, if you want the PaperSprite to rotate around the top left corner, bottom right, or indeed any point on its surface, you can set the pivot property, which is a Point object and requires 2 normalised values, representing the fraction of the width and height of the PaperSprite at which you want to place the pivot.
So to set the PaperSprite to rotate around its centre (this is set by default) you can use:
mySprite.pivot = new Point( 0.5, 0.5 );
And its Top Left corner:
mySprite.pivot = new Point( 0.0, 0.0 );
And its top centre:
mySprite.pivot = new Point( 0.5, 0.0 );
And so on!
You can also access its isFrontFacing property at any time:
if ( mySprite.isFrontFacing )
{
doSomethingGood();
}
An finally, removing the front or back face from its display list (or indeed not defining one at all) will cause the PaperSprite to display the available face at all times, essentially giving it the default behaviour of a one sided Sprite.
Download the PaperSprite class
Again, this is really just a glorified augmentation of Senocular’s solution to finding the front facing side of a DisplayObject in 3D. All credit should go to him for creating such an elegant solution. I built this class in order to simplify its use and provide the extra functionality needed to quickly start working with a two-sided DisplayObject.
Download: PaperSprite Class & Demo
uff…. that is very useful.
Thanks!!
Great post, and thanks for checking out my attempt at a two sided plane. As you pointed, out my example was for basic use like simple flipping effects so your PaperSprite is a nice solution to my TwoSidedPlane’s short comings. I also like the notion of auto update in your class but was wondering if your use of enterFrame would be a little “intensive” if you had lots of these planes on the stage? My attempt to override the getter and setter was to have a passive update only when the property was being changed? Could it be possible to have that in your class? So if you change the x,y, or z you call your update and use stage.invalidate() to keep the display from updating if more the one property was being manipulated at once? I personally try to avoid enterFrame loop events on individual instances of a Class as much as possible since it becomes hard to start and stop multiple instances without some kind of manager class. Also, I tend to have only 1 enterFrame loop, in any of my Flash apps, that updates the necessary displays all at once. I am sure this is out of scope for your example but thought I would add in my 2 cents. I am definitely going to take your solution into consideration and update my TwoSidedPlane!
Hi Jesse,
Thanks for the suggestion. I’ve updated the class and implemented your idea – much cleaner! I’m glad you got in touch; I was sort of rushing to get the thing done in a few spare minutes before New Year’s destroyed all hope of work – I felt it was probably not the best implementation.
Thanks for the lesson and for taking the time to post your thoughts.
The update looks great, glad to help out. Did you recompile the demo at the top of the page with the new code? I would be interesting in knowing if there is any speed improvement? I am going through my framework this holiday and optimizing it so the invalidate stage call has been on my mind. It was brought to my attention by Justin Akin when I was showing him my code. Looking forward to what you post about next…
erm, i’m new to cs4/as3, so sorry for seeming thick…
…but a small pointer is needed – but how do you link to a couple of movieclips for the front and back faces in the above AS code , the displayObject class is very confusing!?!?
Cheers, J
Hi Jay,
MovieClips are DisplayObjects, just a specific type of DisplayObject. If you Google something like “OOP inheritance” you can read up on how this works. This may not be the greatest analogy; but think of it like scientists deal with species – so Flash developers are humans and humans are mamals, so Flash developers are still mamals! (by and large anyway :) just a specific type or mamal, with certain features and abilities, as well as those shared by all mamals.
So a Loader and a MovieClip, for example, are both DisplayObjects as they inherit from the DisplayObject class (and consiquently own the same methods and abilities), however they are also distinctly different from each other because they can each perform their own set of tasks / maintain their own specific qualities etc…
So yes, you can use MovieClips for the front and back – just pass them into the constructor as I showed above and it will work. The reason I defined the front and back as DisplayObjects, rather than MovieClips or Sprites is because this gives a certain flexibility to how you can use the PaperSprite class. Any class that extends the DisplayObject class can be used, and of course MovieClip, just like Shape, Bitmap, Sprite etc, is one of these.
Hope that makes sense!
Hey there :)
This PaperSprite is great ! thanks to share ;)
I just read your post quickly so it may be useless… There is a “native” trick about z-sorting… Thibault Imbert from bytearray.org wrote it in some slides for a flashplayer 10 meeting…
function sortZ():void { var lng:int = paperspriteArray.length; paperspriteArray.sortOn(”z”, Array.DESCENDING | Array.NUMERIC); for (var i:int = 0; i < lng; i++) { setChildIndex(paperspriteArray[i], i); } }Cheers YNK! I think Ralph’s method will work better when there is inherited transformations (so when a clip is inside another rotated clip etc) as it uses getRelativeMatrix3D and accounts for the clips parents, grandparents and so on, but for quick prototyping that’s a nice tidy method! Thanks for the tip :)
hello thank you for the great effect, however I could not use it coz my skills in actionscript is not great, can you send me instruction on how to use or send me fla file which i can adapt. thanks
Hi all,
I’ve posted the code for a quick example above, so you can get a two sided 3D MovieClip or two sided Sprite working very quickly. Also check the update for explanations regarding some other improvements!
Top-notch work man – as always. Thanks for releasing this code!
Hi,
i have added some lines code to ure Class.
In the constructor: addEventListener( Event.ADDED_TO_STAGE, centerStage);
private function centerStage(event:Event):void
{
this.x = stage.stageWidth / 2;
this.y = stage.stageHeight / 2;
}