Drag 'n' Drop MovieClips / Box2D Bodies How To (*UPDATED*)

Attached is a project that demonstrates my solution to attaching MovieClips to Box2D bodies. The advantage of this approach is that you can literally drag 'n' drop bodies from your library into a Box2d world. Once they're on the stage, you can scale & rotate them, as well as set "density" and "isSleeping" via the properties inspector. Here's how it works:

There's 2 main classes - Body and World - that extend MovieClip and correspond to b2Body and b2World classes. Within the attached .fla project, there's an instance of the World symbol on the stage. Within the World symbol are instances of symbols that inherit from Body. When the project is run, the World instance initializes all the bodies and starts the Box2D simulation. For each iteration, the Body-extending MovieClips are updated with data from the Box2d simulation.

So, to "box2d-enable" a symbol, you have to make it extend "Body", then override the "createShapes" function to tell Box2d how your symbol is shaped. There's three examples in the demo - SampleBox, SamplePolygon and SampleCircle.

My goal originally was to parse the MovieClip shape data to create Box2d shapes automatically, but this turned out to be impossible. It doesn't look like you can get raw shape data from a MovieClip during runtime in ActionScript (please correct me if I'm wrong).

I don't know how well this will perform on systems other than my own. Haven't really played around with the FrameRate or b2Settings. I'm justing posting this to help anyone that may be trying to achieve the same effect.
That's awesome Mayo! I've added in Restitution and Friction to the Body.as and I think I'm getting close to having a working revolute joint parameter... I'll post it once (if) i find a way
Good little Example, makes setting up a stage much easier. I look forward to the joint aspect.

Attached is 2 minutes graphic job showing how quick it would be to make a colorful physics stage using components.
hello, and lot of congratulation for this componant.
I've been playing with Box2d since a few week, and my first mission is to create mousejoint or drag effect on this component.
...and choose wish of the component you'd like to set with it...

Badly, i failed.
Can't help find a good way to do it.(maybe that's too hot for newbies).
I prefer think that it has a logical (then simple) solution, but can't get it...

Did someone get it ?
Can share ? Or just help me find the good way (with mystery words) ?? 😀

Many Thanks.
Hey, I am really interested in how you went about creating components from Box2D bodies. Is there anyway you could discuss some of the steps you took to create these components?
Hi, i'd be also interested in it.
I'm curently trying to add a mous joint/drag effect on it to complete this wonderfull toy,
but still have problems by adding it (from the testbed).

if it could help, heres what (one of the test) i've done, but i can't find THE mistake,
here's what you find in the body.as (main thing in the ///////MouseJoint(test)// part) :
Code:
package
{

   import flash.display.MovieClip;
   import flash.events.Event;
   import Box2D.Collision.*;
   import Box2D.Collision.Shapes.*;
   import Box2D.Common.*;
   import Box2D.Common.Math.*;
   import Box2D.Dynamics.*;
   import Box2D.Dynamics.Contacts.*;
   import Box2D.Dynamics.Joints.*;
   import General.Input;

   public class Body extends MovieClip
   {
      public  var mouseXWorldPhys:Number;
      public  var mouseYWorldPhys:Number;
      public  var mouseXWorld:Number;
      public  var mouseYWorld:Number;
      //déclaration du body
      public var body:b2Body;
      public var body_def:b2BodyDef;

      [Inspectable(defaultValue=1)];
      public var density:Number = 1;

      [Inspectable(defaultValue=false)];
      public var isSleeping:Boolean = false;
      //fonction intitialize
      public function initialize ()
      {
         //initialisation de la rotation
         var r:Number = rotation;
         //départ 0
         rotation = 0;
         //ajout de body def, de la classe B2bodydef dans la display liste
         body_def = new b2BodyDef();
         //définition des paramètres : position
         body_def.position.Set (x, y);
         //définition des paramètres : rotation
         body_def.rotation = r * Math.PI / 180;
         //appel à la méthode createShapes (crée Bodydef et sa forme)
         createShapes (body_def);
         //valeur inerte
         body_def.isSleeping = isSleeping;
         //création du body (en fait transformation de la classe, world est défini comme parent, on y crée le bodydef)
         body = (parent as World).world.CreateBody(body_def);
         //utilisation des objets placés sur la scène pour acquérir des propriétés
         body.m_userData = this;
         //méthode onEnterFrame
         MouseDrag ();
         addEventListener (Event.ENTER_FRAME, onEnterFrame);
      }
      //méthode onEnterFrame
      public function onEnterFrame (e:Event)
      {
         //p est égale au vecteur défini en world
         var p:b2Vec2 = b2Math.SubtractVV(body.m_position, b2Math.b2MulMV(body.m_R, body.m_center));
         x = p.x;
         y = p.y;
         rotation = (body.m_rotation * 180) / Math.PI;
      }
      //méthode de création des shapes
      public function createShapes (b:b2BodyDef):void
      {
      }
      public function polygon (points:Array, x_pos:Number = 0, y_pos:Number = 0, rot:Number = 0):b2PolyDef
      {
         var s:b2PolyDef = new b2PolyDef();
         s.vertices = [];
         for each (var p:Array in points)
         {
            s.vertices.push (new b2Vec2(p[0] * scaleX, p[1] * scaleY));
         }
         s.vertexCount = points.length;
         s.localPosition = new b2Vec2(x_pos * scaleX, y_pos * scaleY);
         s.localRotation = rot * Math.PI / 180;
         s.density = density;
         return s;
      }
      public function box (size_x:Number, size_y:Number, x_pos:Number = 0, y_pos:Number = 0, rot:Number = 0):b2BoxDef
      {
         var s:b2BoxDef = new b2BoxDef();
         s.extents = new b2Vec2(size_x / 2 * scaleX, size_y / 2 * scaleY);
         s.localPosition = new b2Vec2(x_pos * scaleX, y_pos * scaleY);
         s.localRotation = rot * Math.PI / 180;
         s.density = density;
         return s;
      }
      public function circle (radius:Number, x_pos:Number = 0, y_pos:Number = 0):b2CircleDef
      {
         var s:b2CircleDef = new b2CircleDef();
         s.radius = radius * scaleX;
         s.localPosition = new b2Vec2(x_pos * scaleX, y_pos * scaleY);
         s.density = density;
         return s;
      }
      
      
      //////
      ///////MouseJoint(test)
      //////
      
      
      public var m_world:b2World;
      public var m_bomb:b2Body;
      public var m_mouseJoint:b2MouseJoint;
      public var m_iterations:int = 10;
      public var m_timeStep:Number = 1/30;
      public var m_physScale:Number = 1;
      
      public function MouseDrag ():void
      {
         // mouse press
         if (Input.mouseDown && !m_mouseJoint)
         {

            var body:b2Body = GetBodyAtMouse();

            if (body)
            {
               var md:b2MouseJointDef = new b2MouseJointDef();
               md.body1 = m_world.m_groundBody;
               md.body2 = body;
               md.target.Set (mouseXWorldPhys, mouseYWorldPhys);
               md.maxForce = 30000.0 * body.m_mass;
               md.timeStep = m_timeStep;
               m_mouseJoint = m_world.CreateJoint(md) as b2MouseJoint;
               body.WakeUp ();
            }
         }
         // mouse release
         if (!Input.mouseDown)
         {
            if (m_mouseJoint)
            {
               m_world.DestroyJoint (m_mouseJoint);
               m_mouseJoint = null;
            }
         }
         // mouse move
         if (m_mouseJoint)
         {
            var p2:b2Vec2 = new b2Vec2(mouseXWorldPhys, mouseYWorldPhys);
            m_mouseJoint.SetTarget (p2);
         }
      }
      //======================
      // GetBodyAtMouse
      //======================
      private var mousePVec:b2Vec2 = new b2Vec2();
      public function GetBodyAtMouse (includeStatic:Boolean=false):b2Body
      {
         // Make a small box.
         mousePVec.Set (mouseXWorldPhys, mouseYWorldPhys);
         var aabb:b2AABB = new b2AABB();
         aabb.minVertex.Set (mouseXWorldPhys - 0.001, mouseYWorldPhys - 0.001);
         aabb.maxVertex.Set (mouseXWorldPhys + 0.001, mouseYWorldPhys + 0.001);

         // Query the world for overlapping shapes.
         var k_maxCount:int = 10;
         var shapes:Array = new Array();
         var count:int = m_world.Query(aabb, shapes, k_maxCount);
         var body:b2Body = null;
         for (var i:int = 0; i < count; ++i)
         {
            if (shapes[i].m_body.IsStatic() == false || includeStatic)
            {
               var inside:Boolean = shapes[i].TestPoint(mousePVec);
               if (inside)
               {
                  body = shapes[i].m_body;
                  break;
               }
            }
         }
         return body;
      }
      public function UpdateMouseWorld ():void
      {

         mouseXWorldPhys = (Input.mouseX);
         mouseYWorldPhys = (Input.mouseY);
         mouseXWorld = (Input.mouseX);
         mouseYWorld = (Input.mouseY);
      }
      
      
   }
}


and added this simple line in the world class (in the activate method)
Code:
c.initialize ();
               c.UpdateMouseWorld ();


Idea, anybody ???

Thanks.
Hi Gabin,

There are quite a few things here that just won't work...

1. the c.UpdateMouseWorld (); in the World.as would only be called as many times as there are bodies on the stage because of:
Code:
for(var i:Number = 0; i < numChildren; i++) {
   c = getChildAt(i) as Body;
      if(c) {
         c.initialize();      
      }
}


2. Same goes for your MouseDrag (); because you are containing it within that initialize function so it will only be called for every body.

3. you are assuming that the input.as will just work by copying it over from the testbed... you need to take a look at that file....

4. IF (and that's a big IF), you are wanting to do a cut & paste method of trying to make this work, i would suggest making use of the trace function to narrow down problems. For instance, if you place a trace after "if (Input.mouseDown && !m_mouseJoint)", is it even recognizing the mouse is down? if so, trace mouseXWorld, is it coming back with the proper coordinate?

Overall, i would suggest starting your own project from scratch (try using tyler's basic world example - http://www.tyleregeto.com/?p=84) and then build from that so you get a better understanding of how it all works.

-Bryan
Hi Bryan,
thanks a lot for your answers,
i missed a lot of things, and the first was time (and concentration)...
As you can see, there's no even mouse call...
it was late...

But what you said is very interisting, in fact as you understood, i want every bodies on the scene to be dragged and moved as long as i click on them, so why not to assign the mousedrag function on every of the bodies instanced "c" (as lon as i add a mouse call for that ???
Or can't the UpdateMouseWorld, can be called every frame ?

I don't understand the problem by importing the output class ??

For the rest you are right...
We don't always have the time that such a passionate quest requier (whereas small steps always make big journeys...) 😉

THnks and maybe i'll have the chance to get even more of those good words i the future.
Hey Gabin,

Try this for your Body.as, I kinda threw it together so im sure there is a better way to do this, but as long as your 'world' movieClip is at 0,0 then it should do the trick:
Code:
package {

   import flash.display.MovieClip;
   import flash.events.Event;
   import flash.events.*;
   import Box2D.Collision.*;
   import Box2D.Collision.Shapes.*;
   import Box2D.Common.*;
   import Box2D.Common.Math.*;
   import Box2D.Dynamics.*;
   import Box2D.Dynamics.Contacts.*;
   import Box2D.Dynamics.Joints.*;

   public class Body extends MovieClip {

      public var m_world:b2World;
      public var body:b2Body;
      public var body_def:b2BodyDef;
      public var mj:b2MouseJoint;
      public var md:b2MouseJointDef;
      public var m_timeStep:Number = 1/30;
      public var mouseDown:Boolean = false;


      [Inspectable(defaultValue=1)];
      public var density:Number = 1;

      [Inspectable(defaultValue=false)];
      public var isSleeping:Boolean = false;

      public function initialize() {
         m_world = (parent as World).world;
         var r:Number = rotation;
         rotation = 0;
         body_def = new b2BodyDef();
         body_def.position.Set(x, y);
         body_def.rotation = r * Math.PI / 180;
         createShapes(body_def);
         body_def.isSleeping = isSleeping;
         body = m_world.CreateBody(body_def);
         body.m_userData = this;
         this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDrag);
         addEventListener(Event.ENTER_FRAME, onEnterFrame);

      }
      public function mouseDrag(e:Event):void {

         mouseDown = true;

         if (!mj) {
            var p:b2Vec2 = b2Math.SubtractVV(body.m_position, b2Math.b2MulMV(body.m_R, body.m_center));
            md = new b2MouseJointDef();
            md.body1 = m_world.m_groundBody;
            md.body2 = body;
            md.target.Set(p.x, p.y);
            md.maxForce = 5000000 * body.m_mass;
            md.timeStep = m_timeStep;
            mj = m_world.CreateJoint(md) as b2MouseJoint;
            body.WakeUp();
         }
         stage.addEventListener(MouseEvent.MOUSE_UP, dmJoint, false, 0, true);
         stage.addEventListener(MouseEvent.MOUSE_MOVE, mJoint, false, 0, true);


         function mJoint(e:MouseEvent):void {

            if (mj && (mouseDown == true)) {

               var p2:b2Vec2 =  new b2Vec2(e.stageX, e.stageY);
               mj.SetTarget(p2);
            }
         }


         function dmJoint(e:MouseEvent):void {
            if (mouseDown == true) {
               mouseDown = false;
               if (md) {
                  m_world.DestroyJoint(mj);
                  mj = null;
                  md = null;
               }
            }
         }
      }

      public function onEnterFrame(e:Event) {
         var p:b2Vec2 = b2Math.SubtractVV(body.m_position, b2Math.b2MulMV(body.m_R, body.m_center));
         x = p.x;
         y = p.y;
         rotation = (body.m_rotation * 180) / Math.PI;
      }
      public function createShapes(b:b2BodyDef):void {
      }
      public function polygon(points:Array, x_pos:Number = 0, y_pos:Number = 0, rot:Number = 0):b2PolyDef {
         var s:b2PolyDef = new b2PolyDef();
         s.vertices = [];
         for each (var p:Array in points) {
            s.vertices.push(new b2Vec2(p[0] * scaleX, p[1] * scaleY));
         }
         s.vertexCount = points.length;
         s.localPosition = new b2Vec2(x_pos * scaleX, y_pos * scaleY);
         s.localRotation = rot * Math.PI / 180;
         s.density = density;
         return s;
      }
      public function box(size_x:Number, size_y:Number, x_pos:Number = 0, y_pos:Number = 0, rot:Number = 0):b2BoxDef {
         var s:b2BoxDef = new b2BoxDef();
         s.extents = new b2Vec2(size_x / 2 * scaleX, size_y / 2 * scaleY);
         s.localPosition = new b2Vec2(x_pos * scaleX, y_pos * scaleY);
         s.localRotation = rot * Math.PI / 180;
         s.density = density;
         return s;
      }
      public function circle(radius:Number, x_pos:Number = 0, y_pos:Number = 0):b2CircleDef {
         var s:b2CircleDef = new b2CircleDef();
         s.radius = radius * scaleX;
         s.localPosition = new b2Vec2(x_pos * scaleX, y_pos * scaleY);
         s.density = density;
         return s;
      }
   }
}
Thanks a lot Bryan,
I haven't take a long look at it, but what i get is more an impulse on mouse move than real dragging ??
>>That's it, (I've just opened it), every clip move in the defined vector on mJoint function.
but do not follow it.

So, I visualize much more on my mistakes.
Let me a small time to try get what I wanted from what you gave me !
I'm pretty optimistic now.

Read you soon (I hope).

Original thread: https://box2d.org/forum/viewtopic.php?t=367