diamondTearz

diamondTearz- half MD- half Machine

diamondTearz header image 2

Exploring the ActionScript Physics Engine in Flex

June 3rd, 2008 · 2 Comments

What we are building:

I’ve found that one of the quickest ways to get familiar with an API is to create a Playground testing the features of the API. With that in mind we’re building an app that allows the user to experiment with some of the basic settings of the APE (Actionscript physics engine by Alex Cove).

I decided to use the Flex Framework for this and am not putting this forth as an example of a well architected application. It just works and actually grew organically as I was experimenting with other features. I welcome any feedback as far as parts that need clarification or any other changes that I could make that would make this post more useful.

Background:

The Ape engine provides a small library of classes that allow the user to simulate rigid body physics using actionscript. It’s the next generation of the Flade Engine, which used Verlet Integration for rapid physics emulation.

In this walkthrough I’m assuming that the developer is familiar with Flex Builder IDE and is familiar with ActionScript 3.0. I am therefore focusing on the details of the code instead of project setup.

APE can be downloaded at Alex Cove’s site . I prefer to use the Source files so that I’m able to troubleshoot by tracking through the code.

Create A new Flex Project Named ApePlayground

2. Create an externals library in your project folder and add the contents of the source folder from APE into that folder.

3. Add the externals folder to your source path and you are ready to go.

4. The first thing we are going to do is set up the general control panel in MXML.

5. Add the following two methods in your mx:Script tag

        import org.cove.ape.RectangleParticle;
        import org.cove.ape.AbstractParticle;
        import org.cove.ape.Group;
        import org.cove.ape.CircleParticle;
        import org.cove.ape.Vector;
        import org.cove.ape.APEngine;

        private var contentHolder:Sprite=new Sprite();
        private var defaultGroup:Group;

        private function initApp():void{
                spriteWrapper.addChild(contentHolder);
                addEventListener(Event.ENTER_FRAME,run);
                //initialize the engine lower=slower
                APEngine.init(1/4);
                //provide engine with a view to use as a renderer
                APEngine.container=contentHolder;
                //add a vertical force to simulate gravity
                APEngine.addMasslessForce(new Vector(0,2));
               //create the default group of particles
               defaultGroup=new Group(); APEngine.addGroup(defaultGroup);
              //members of the group will collide with each other on contact
              defaultGroup.collideInternal=true;
              //create ground
              var ground:RectangleParticle=new RectangleParticle(this.width/2,this.height-200,this.width-50,10,0,true);
             ground.setFill(0xCCCCCC);
             defaultGroup.addParticle(ground);
             APEngine.addGroup(defaultGroup);
    }

The initApp() method wraps the contentHolder -which is a Sprite and not a UICompomponent to allow it to be added to a container without causing an error. The APEngine is initialized by calling the init() method and passing it a value that determines the rate of the simulation. A group is also created- this represents a virtual space/collection with members able to collide and interact.

private function run():void{
    APEngine.step();
    APEngine.paint();
 }

The run method called by the Event.EnterFrame event at the rate of frame refresh. Within it are two mothers the step() method advances the events on the APEngine. The paint() method then calls the paint() method on all of it’s child particle and constraint elements (see composite design pattern)

That covers initializing the engine. Next We’ll look at adding actual content to the engine.

Particles

The visible elements in the engine are represented by particle. Our particles extend the abstract class AbstractParticle which provide position, mass, elasticity,friction and isFixed values. The AbstractParticle class also allows forces to be applied to the particle and some other features that we’ll explore later.

private function createCircle():AbstractParticle{
     var circle:CircleParticle=new CircleParticle(mousePosition.x,mousePosition.y,circleRadius.value,isFixed.selected,1,.1);
     return circle; }

The CircleParticle can be added to the system using the following constructor (xPosition,yPosition,radius,isFixed,mass,elasticity). we’re using a bit of a factory method here to allow us flexibility in adding ParticleCreators.

    private function addSelectedParticle():void{
        var createdParticle:AbstractParticle;
        createdParticle=createCircle();
        createdParticle.setFill(itemColor.selectedColor);
       defaultGroup.addParticle(createdParticle);
    }

We add this helper method into our script block so that we can use our mouseDown as follows to create the selected particle.

    //place at the top of the script block with other variables
     private var mousePosition:Point
     private function onMouseDown(e:MouseEvent):void{
         mousePosition=new Point(e.localX,e.localY);
         addSelectedParticle()
     }

you will also add the following to the initApp Method to listen for MouseEvent.MOUSE_DOWN on the canvas

viewScreen.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);

Link to full sized version

A more feature complete but less tested version-with multiple particles implemented

Tags: Flash

2 responses so far ↓

  • 1 Ronny Karam // Jun 10, 2008 at 7:27 am

    Hi,

    I really appreciate the engine you’re building. I didn’t read the whole article to see if u mentioned any bugs, i was so excited that i scrolled down the button to check the demo. Still, if u “triple click” u’ll have 2 circles bouncing above each other (same y). They keep on bouncing till one get stuck in the horizontal bar and actually penetrates the bar to the other side.

    Regards,

    Ronny Karam
    Flash/web developer

  • 2 Tuorials | AS3 and Physics « Flash Enabled Blog // Sep 3, 2008 at 6:57 pm

    [...] Exploring the ActionScript Physics Engine in Flex [...]

Leave a Comment