Build 10 classic Flash games and learn game development along the way with this ultra-fast paced game development course.

If you love this blog, this is the book for you.

Buy the book

Get the source code of 12 commercial Flash games, which have been loaded more than 50 million times!

Learn from real world successful examples.

Get it now

Box2D for Flash Games teaches you how to make Flash physics games from scratch with the most advanced features.

Create the new Flash game smashing hit.

Buy the book

APE – Actionscript Physics Engine tutorial

October, 23rd update: Part 2 released

With the increasing performances of Actionscript and modern computers, now we have enough power to simulate physics in a Flash movie.

All we need is… let’s say… an huge knowledge of physics, constraints, integrations and so on. With all those things to think about, we cannot focus on the main goal: produce our game/application.

Someone should develop an Actionscript physics engine… APE (Actionscript Physics Engine) is a free AS3 open source 2D physics engine for use in Flash and Flex, released under the MIT License.

I started playing with it yesterday, and results are really amazing. While I need much more time for some experiments, I want to share with you my first steps.

The documentation about this project is very poor (some kind of API without examples, one tutorial and two demos….) so this tutorial could be a bit unclear, but I am doing my best.

Moreover, it’s my first time with APE and my first time with Flex… two new tools to learn quickly, but I am a geek and I am a PROgrammer, so that’s no problem!

First, download the alpha version (yes… just an alpha…).

Now, we need Flex. Let’s say Flex 2. From its official site: “Adobe® Flexâ„¢ 2 is a cross-platform development framework for creating rich Internet applications (RIAs). Flex enables you to create expressive, high-performance applications that run identically on all major browsers and operating systems.”

If it’s your first time with Flex, you can download a complete 30 days evaluation version from this page.

When you have Flex installed on your computer the unzipped APE folder, you are ready to go.

Launch Flex and create a new ActionScript project

APE

Call you project “ape” (you can call it as you want, but later in the code you will have to use this name, so if it’s your first time call it “ape”), don’t click on “Finish” but go to “Next >”.

APE

Seletc “Library Path” and click on “Add SWC…”

APE

Now in the dialog box select the ape.swc file, normally located in the bin directory of your APE package, then click OK and Finish.

APE

You should have an actionscript window with this content:

The public class ape and public function ape are called in this way because I named the project ape.

Now it’s time to show you what can I do in less than 40 lines

Lines 2-4: Importing necessary libraries

Line 5: Setting width, height, bgcolor and framerate of the movie we are going to create. This is the way you have to define attributes in pure actionscript projects.

Note: Width and height must be specified in pixels. You are not allowed to use percentage values such as 50%.

Line 6: Definining the ape class as an extension of the built in Sprite class.

The Sprite class is new in ActionScript 3.0 A Sprite object is similar to a movie clip, but does not have a timeline.

Line 7: Declaring the main function

Line 8: Adding an event listener. Since the on(event) syntax is no longer supported in ActionScript 3.0, we need to use addEventListener to trig for some events. In our case, the event is ENTER_FRAME. So it’s basically an onEnterFrame = function(){} coded in AS3, where the “function” is run (the function defined at lines 32-35).

Line 9: Initializing the APE engine. The parameter 1/4 (0.25) is used to set the speed of the simulation. Typical values are 1/3 or 1/4. Lower values result in slower, but more accurate simulations, and higher ones result in faster, less accurate ones.

Line 10: Definining the default container used by the default painting methods of the particles and constraints. In other words, the area where the simulation takes place.

Line 11: Adding a “massless” force to the system. What is a “massless” force? It’s a force that acts on all particles in the same way even if they have different masses… such as gravity. Particles with larger masses are affected by gravity same as those with smaller masses. The Vector represents the… vector of the force, splitted in fx and fy. fx is the horizontal component of the force, while fy is the vertical component of the force. In our case, we have a force that does not have horizontal force, but only a vertical one (like gravity). Changing the vector values will result in different gravity types (reverse, horizontal, and so on).

Line 12: Creating a group called defaultGroup. The Group class can contain Particles, Constraints, and Composites. Groups can be assigned to be checked for collision with other Groups or internally. This means that I can have a group of particles that can collide only with particles of another group, or a group of particles that are checked for collision one with each other. As you can see from Line 13, I want my particles inside defaultGroup to collide, and I specify it with the collideInternal property

Line 14: Creating a circle haped particle. The CircleParticle has some interesting parameters:

x:Number: The initial x position of this particle.

y:Number: The initial y position of this particle.

radius:Number: The radius of this particle.

fixed:Boolean (default = false): Determines if the particle is fixed or not. Fixed particles are not affected by forces or collisions and are good to use as surfaces. Non-fixed particles move freely in response to collision and forces.

mass:Number (default = 1): The mass of the particle.

elasticity:Number (default = 0.3): The elasticity of the particle. Higher values mean more elasticity or “bounciness”.

friction:Number (default = 0): The surface friction of the particle

So in my case I have a circle particle located at (250,10) with a radius of 5 pixels, that is not fixed (it will fall, bounce, etc), with a mass equal to 1 and an elasticity equal to 0.3 and no friction.

Line 15: Adding the circle particle to the group defined at line 12

Line 16: Introducing the most interesting particle of the engine, in my opinion: the wheel particle. A wheel particle is… a particle that simulates the behavior of a wheel.

Let’s see its parameters:

x:Number: The initial x position.

y:Number: The initial y position.

radius:Number: The radius of this particle.

fixed:Boolean (default = false): Determines if the particle is fixed or not. Fixed particles are not affected by forces or collisions and are good to use as surfaces. Non-fixed particles move freely in response to collision and forces.

mass:Number (default = 1): The mass of the particle

elasticity:Number (default = 0.3): The elasticity of the particle. Higher values mean more elasticity.

friction:Number (default = 0): The surface friction of the particle.

traction:Number (default = 1): The surface traction of the particle.

So basically a wheel is a circle that can rotate and with a traction

Line 17: Adding the wheel particle to the group

Line 18: Another particle… this time a rectangle particle. Look at the parameters:

x:Number: The initial x position.

y:Number: The initial y position.

width:Number: The width of this particle.

height:Number: The height of this particle.

rotation:Number (default = 0): The rotation of this particle in radians. Read carefully! RADIANS!!

fixed:Boolean (default = false): Determines if the particle is fixed or not. Fixed particles are not affected by forces or collisions and are good to use as surfaces. Non-fixed particles move freely in response to collision and forces.

mass:Number (default = 1): The mass of the particle

elasticity:Number (default = 0.3): The elasticity of the particle. Higher values mean more elasticity.

friction:Number (default = 0): The surface friction of the particle.

Line 19: Adding the rectangle particle to the group

Lines 20-23: Adding two more rectangle particles

Lines 24-27: Adding two more wheel particles

Line 28: The feature I love: the spring constraint. The spring constraint is a spring-like constraint that connects two particles. If you need more information about constraints, refer to Creation of a Ragdoll with Flash part 2: Constraints.

I am going to connect the last two wheels I created with a constraint. This means I am going to create a car. Look at the parameters:

p1:AbstractParticle: The first particle this constraint is connected to.

p2:AbstractParticle: The second particle this constraint is connected to.

stiffness:Number (default = 0.5): The strength of the spring. Valid values are between 0 and 1. Lower values result in softer springs. Higher values result in stiffer, stronger springs.

collidable:Boolean (default = false): Determines if the constraint will be checked for collision

rectHeight:Number (default = 1): If the constraint is collidable, the height of the collidable area can be set in pixels. The height is perpendicular to the two attached particles.

rectScale:Number (default = 1): If the constraint is collidable, the scale of the collidable area can be set in value from 0 to 1. The scale is percentage of the distance between the the two attached particles.

scaleToLength:Boolean (default = false): If the constraint is collidable and this value is true, the collidable area will scale based on changes in the distance of the two particles.

In my case, I am connecting the last two wheels with a semi-strong collidable spring, with an height of 3 pixels.

Line 29: Adding the constraint to the group

Line 30: Adding the group to the engine

Line 32: Beginning of the function to be executed at every frame, like declared at line 8

Line 33: The main step function of the engine. This method should be called continously to advance the simulation. The faster this method is called, the faster the simulation will run. Usually you would call this in your main program loop.

Line 34: Calling this method will in turn call each particle and constraint’s paint method. Generally you would call this method after stepping the engine in the main program cycle.

The last two lines advance the simulation and display the result.

And this is what I got with this simple script (you may need to reload the page to see the movie work properly)

As you can see, results are really exciting. The ball, the wheel and the car go down the slope bouncing and moving in a very realistic way. I am sure I will be able to create a “Moster Truck” game in a few hours.

And I’ll publish it as soon as it create it.

Meanwhile, download the entire project and give me feeback. Then, move to part 2

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (12 votes, average: 4.33 out of 5)
Loading ... Loading ...
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 30 comments

  1. chaew

    on October 14, 2007 at 12:59 am

    whoa d00d thats awesome!

  2. Thomas

    on October 14, 2007 at 8:14 am

    amazing use of physics!

    though flex doesn’t work on vista x64. sigh.

  3. Samuel

    on October 14, 2007 at 1:36 pm

    I’m sorry for asking, but what differences must be implemented if I wish to recreate this excact same animation in Flash, not Flex?

    This is definitively a engine I will use and learn, it’s AMAZING! Thanx for sharing this with us!

  4. Samuel

    on October 14, 2007 at 2:16 pm

    Aah, I figured it out…

    Save the code in ape.as, but remove the line that starts with:
    [SWF…

    Then use the ape.as as the document class, and it works just as well as it would have done in Flex :)

    Now I’m starting to experiment!

  5. Michael

    on October 14, 2007 at 8:46 pm

    WOW! That is absolutely amazing.

    I hate getting pumped on something when I suck at Flash, lol.

    I can just imagine the cool games people can make with a package like this. It looks very good.

  6. fluxa

    on October 17, 2007 at 5:55 pm

    hi, nice tutorial.
    How can I attach a movieclip to an APE particle like WheelParticle in order to apply physics properties to other flash objects.

  7. Kevin

    on October 23, 2007 at 12:22 pm

    Why is the small wheel rolling so slow on the first slope?

  8. APE - Actionscript Physics Engine tutorial - Part 2 : Emanuele Feronato - blog of an italian geek

    on October 23, 2007 at 6:07 pm

    [...] strongly recommend you to read the first part before [...]

  9. David

    on October 24, 2007 at 6:01 pm

    brilliant

  10. Crack CBSE

    on November 16, 2007 at 9:43 am

    I found this great site with physics, maths and chemistry assignments http://crackcbse.in

  11. Box2DFlashAS3 - a library to watch : Emanuele Feronato - italian geek and PROgrammer

    on November 30, 2007 at 12:46 am

    [...] I’ll keep on studying APE, but I have to admit that Box2D-based phyiscs engines look [...]

  12. Adam

    on December 12, 2007 at 11:21 am

    Cool, nice discussion of the code. I keep meaning to do the same with my stuff on Papervision

  13. David Says: Perhaps I should be using APE… « FTV488B’s Weblog

    on March 17, 2008 at 11:45 am

    [...] http://www.emanueleferonato.com/2007/10/14/ape-actionscript-physics-engine-tutorial/  [...]

  14. blog Boreal Kiss» ブログアーカイブ » [FLASH]ばくだんいわが あらわれた!

    on April 17, 2008 at 1:23 pm

    [...] ActionScript 3.0の開発環境が整いつつあったので前々からいじってみたかったAPE (Actionscript Physics Engine)という物理演算パッケージを使ってみた。APEについてる仕様書はちょっとわかりにくいので外部チュートリアルまかせ。Flex版チュートリアルとFlash CS3版チュートリアルなんかがとっつきやすかった(Many thaks to Emanuele Feronato)。見よう見まねでパッケージ内で定義されてるWheelParticleクラスに(丸くて手頃だった)ばくだんいわの画像を貼付けただけなんだけど割と好評。APEの実装より背景画像作る方が時間かかったかな。 [...]

  15. Flash physics engines galore : Emanuele Feronato - italian geek and PROgrammer

    on April 24, 2008 at 10:55 am

    [...] can also find two tutorials on my blog here and [...]

  16. devis

    on August 21, 2008 at 9:48 am

    hi i’m making a game i flash8..’bike ride’ but stuck with the physics part…..the collisions with obstacles and other things…………can u help?

  17. Tuorials | AS3 and Physics « Flash Enabled Blog

    on September 4, 2008 at 1:56 am

    [...] APE – Actionscript Physics Engine tutorial – Part 1 [...]

  18. Sajan

    on September 6, 2008 at 5:09 am

    WoW, Wonderful

  19. Matt Howarth

    on December 18, 2008 at 1:36 pm

    Hi Emanuele,

    fantastic tutorial as ever.

    Will ape objects respond to ordinary commands like rotate etc?

    cheers

    Matt

  20. Colisiones y motores de física en Action Script | 2flash2furious :: diseño gráfico, web & multimedia :: por [Q] interactiva

    on September 21, 2009 at 6:04 pm

    [...] Aquí os dejamos un tutorial de regalo. Y su segunda parte. [...]

  21. Rapport Flash Fysik Ape vs Box2D › Title

    on January 4, 2010 at 3:32 pm

    [...] http://www.emanueleferonato.com/2007/10/14/ape-actionscript-physics-engine-tutorial/ (Ape) [...]

  22. Inxentas

    on September 13, 2010 at 9:14 am

    The only thing I dislike about APE is the fact it causes a naming conflict with the Vector class when compiling for FP10. This can be fixed by renaming APE’s Vector class though. It’s very easy to use and easy to implement.

  23. flex??:APE?????? | flex??|flex ????|flex ??|flex java|jinFlex

    on October 23, 2010 at 2:56 am

    [...] ????DEMO????? http://www.garrahan.org/ape/?cat=3 ?FLEX????? http://www.emanueleferonato.com/2007/10/14/ape-actionscript-physics-engine-tutorial/ ?flash cs3????? [...]

  24. Pavel

    on November 20, 2010 at 10:57 pm

    Good engine! Im really thinking about it in my game. Tell me please – Does this engine have a force? (as example radius/mass/dimension)? Im really need this and dont know how i can realize it with help this engine. PS I write on AS3.

  25. Pavel

    on November 20, 2010 at 10:59 pm

    update
    APEngine.addMasslessForce(new Vector(0,2));

    What mean this MasslessForce? Dimension? Several massless force (as example planets)?

  26. Pavel

    on November 20, 2010 at 11:00 pm

    update 2… Oh sorry sorry i mean NAPE engine!!!!!!!!

  27. Rapport Flash Fysik Ape vs Box2D › Dinolab

    on August 30, 2011 at 4:16 pm

    [...] http://www.emanueleferonato.com/2007/10/14/ape-actionscript-physics-engine-tutorial/ (Ape) [...]

  28. R Star

    on September 9, 2011 at 3:07 pm

    Hi,

    While I try to run the application I get two errors of code line no 11.

    1067: Implicit coercion of a value of type_AS3_.vec:Vector to an unrelated type org.cove.ape:Vector
    1137: Incorrect number of arguments. Expected no more than 0

    Can any one solve out these errors?

  29. mySelf

    on April 16, 2012 at 8:24 pm

    Change your version of flash player to something below version 10 and it should be fixed now.

  30. Thiago Bardez

    on May 3, 2012 at 7:16 pm

    To use this class in Flash AS3, do you change the name of the class VECTOR to other name, because the base of the As3 contains the VECTOR class and a conflict will appear.

    I think resolve so much of problems.

    ;)