constant mouse joint on an Avatar

Hi,

I'm new to Box2dFlash.

I'm trying to expand an existing game that I made in the past with the Box2dFlash physics engine.

In the old version the Avatar is constantly attached to the mouse. This was a very dirty solution.

Because of this I want use a constant mouse joint on the Avatar to give the avatar a more realistic feel.

How can I achieve this? In the example files they always use a temporary mouse joint on an object when the mouse button is down. Making a permanent mouse joint should be easier right?

Here's the code I have right now:

Code:
package {

   import flash.display.Sprite;
   import flash.events.Event;
   // Classes used in this example
   import Box2D.Dynamics.*;
   import Box2D.Collision.*;
   import Box2D.Collision.Shapes.*;
   import Box2D.Common.Math.*;
   import flash.display.MovieClip

   public class Main extends MovieClip{

      private var stageWidth:Number  = 800;
      private var stageHeight:Number = 600;
      
      private var worldAABB:b2AABB = new b2AABB();      // define world object
      private var gravity:b2Vec2 = new b2Vec2(0.0, 0.0);   // define gravity vector
      private var doSleep:Boolean = true;               // Allow bodies to sleep when not moving
      
      private var worldScale:Number = 30;

      private var iterations:int = 10;
      private var timeStep:Number = 1/30;

      public function Main(){   

         addEventListener(Event.ENTER_FRAME, Update, false, 0, true);   // Add event for main loop
      
         createWorld();
         createReqjec();
         createRequester();
         createAvatar();

         // Vars used to create bodies
//         var requesterDef:b2CircleDef;      // create requester body
//         var reqjecDef:b2CircleDef;         // create reqjec body
//         var avatarDef:b2CircleDef;         // create avatar body
         var body:b2Body;
         var bodyDef:b2BodyDef;
      }
      
      // create World
      private function createWorld():void
      {
         worldAABB.lowerBound.Set(-100.0, -100.0);   // set world boundaries (not stage!) must be > stage
         worldAABB.upperBound.Set(100.0, 100.0);      // set world boundaries (not stage!) must be > stage
         
         m_world = new b2World(worldAABB, gravity, doSleep);      // create world object
      }

      // add Requester
      private function createRequester():void
      {
         var bodyDef = new b2BodyDef();
         bodyDef.position.x = stageWidth / 2 / worldScale;
         bodyDef.position.y = stageHeight / 2 / worldScale;
         
         var requesterDef = new b2CircleDef();
         requesterDef.radius = 1.5;
         requesterDef.density = 1.0;
         requesterDef.friction = 0.5;
         requesterDef.restitution = 0.2
         bodyDef.userData = new Requester();
         bodyDef.userData.width = requesterDef.radius * 2 * 30;
         bodyDef.userData.height = requesterDef.radius * 2 * 30;
         var body = m_world.CreateBody(bodyDef);
         body.CreateShape(requesterDef);

         //confirm if this is correct syntax!!!
         body.SetMassFromShapes();
         addChild(bodyDef.userData);
      }
      
      // create Avatar
      private function createAvatar():void
      {
         var bodyDef = new b2BodyDef();
         bodyDef.position.x = 200 / worldScale;
         bodyDef.position.y = 450 / worldScale;
         
         var avatarDef = new b2CircleDef();
         avatarDef.radius = 1.1;
         avatarDef.density = 1.0;
         avatarDef.friction = 0.5;
         avatarDef.restitution = 0.2
         bodyDef.userData = new Avatar();
         bodyDef.userData.width = avatarDef.radius * 2 * 30;
         bodyDef.userData.height = avatarDef.radius * 2 * 30;
         var body = m_world.CreateBody(bodyDef);
         body.CreateShape(avatarDef);
         
         //confirm if this is correct syntax!!!
         body.SetMassFromShapes();
         addChild(bodyDef.userData);
      }
      
      // add Reqjec
      private function createReqjec():void
      {
         var bodyDef = new b2BodyDef();
         bodyDef.position.x = 750 / worldScale;
         bodyDef.position.y = 50 / worldScale;
         
         var reqjecDef = new b2CircleDef();
         reqjecDef.radius = 0.6;
         reqjecDef.density = 1.0;
         reqjecDef.friction = 0.5;
         reqjecDef.restitution = 0.2
         bodyDef.userData = new Reqjec();
         bodyDef.userData.width = reqjecDef.radius * 2 * 30;
         bodyDef.userData.height = reqjecDef.radius * 2 * 30;
         var body = m_world.CreateBody(bodyDef);
         body.CreateShape(reqjecDef);
         
         //confirm if this is correct syntax!!!
         body.SetMassFromShapes();
         addChild(bodyDef.userData);
      }
         
      
      public function Update(e:Event):void{
         
         m_world.Step(m_timeStep, m_iterations);
         
         // Go through body list and update sprite positions/rotations
         for (var bb:b2Body = m_world.m_bodyList; bb; bb = bb.m_next){
            if (bb.m_userData is Sprite){
               bb.m_userData.x = bb.GetPosition().x * 30;
               bb.m_userData.y = bb.GetPosition().y * 30;
               //bb.m_userData.rotation = bb.GetAngle() * (180/Math.PI);
            }
         }
      }
      
      public var m_world:b2World;
      public var m_iterations:int = 10;
      public var m_timeStep:Number = 1.0/30.0;
      
   }

}
Take a look at MouseInteraction.as in the attached zip file, and PhysicsApp.as to see how to use it.

For your particular application, just take the code from the mouseDown method and place it in the class constructor instead. And of course - you'll need to add a 4th parameter to the constructor for the body you're wanting to attach (and remove the getBodyAtMouse method).

Of course there are a couple of other minor modifications you'll have to make - but if they're not obvious, the errors will let you know. 😉
I was already halfway:

Exception is that read and translate the mouse coordinates in another way:

Code:
mouseXWorldPhys = mouseX/m_physScale;
mouseYWorldPhys = mouseY/m_physScale;

mouseXWorld = mouseX;
mouseYWorld = mouseY;


This is working correctly when I trace.

I do still have one question:

Code:
var body:b2Body =          
if(body)
{         
   var md:b2MouseJointDef = new b2MouseJointDef();
   md.body1 = m_world.m_groundBody;
   md.body2 = body;
   md.target.Set(mouseXWorld, mouseYWorld);
   md.maxForce = 300.0 * body.m_mass;
   m_mouseJoint = m_world.CreateJoint(md) as b2MouseJoint;
}


What can I add to the following code that the MouseJoint will be attached to the Avatar?

Code:
var body:b2Body =


Here's the code for the Avatar:

Code:
// create Avatar
private function createAvatar():void
{
   var bodyDef = new b2BodyDef();
   bodyDef.position.x = 200 / m_physScale;
   bodyDef.position.y = 450 / m_physScale;
         
   var avatarDef = new b2CircleDef();
   avatarDef.radius = 1.1;
   avatarDef.density = 1.0;
   avatarDef.friction = 0.5;
   avatarDef.restitution = 0.2
   bodyDef.userData = new Avatar();
   bodyDef.userData.width = avatarDef.radius * 2 * 30;
   bodyDef.userData.height = avatarDef.radius * 2 * 30;
   var body = m_world.CreateBody(bodyDef);
   body.CreateShape(avatarDef);
         
   //confirm if this is correct syntax!!!
   body.SetMassFromShapes();
   addChild(bodyDef.userData);
}


I'm guessing that I have to "pull" the body out of: m_world.m_bodyList? (I just dunno the right Syntax)

Because I use m_world.m_bodyList to go through my list of sprites:

Code:
// Go through body list and update sprite positions/rotations
for (var bb:b2Body = m_world.m_bodyList; bb; bb = bb.m_next)
{
   if (bb.m_userData is MovieClip){
   bb.m_userData.x = bb.GetPosition().x * 30;
   bb.m_userData.y = bb.GetPosition().y * 30;
   //bb.m_userData.rotation = bb.GetAngle() * (180/Math.PI);
}


This is working correctly and all sprites fall to the ground and bounce on the "surface".
Ok verso I did as you told me. I put in the class and added a fourth parameter for the avatar. When I make the mousejoint I say: md.body2 = avatar;

With the following code in my main file I should get it working right?

Code:
private var avatarMovement:AvatarMovement;

avatarMovement = new AvatarMovement(m_world, this.stage, m_physScale, ???????????);


Now my question is what do I put instead of the ???????????. If I'm correct I have to put the body name of my Avatar there. But how do I know what it is?

You can see the code for my Avatar in my previous post.

Here's the full class code:
(0 errors)


Code:
package {

   import flash.events.MouseEvent;
   import flash.display.DisplayObject;
   import Box2D.Common.Math.*;
   import Box2D.Dynamics.*;
   import Box2D.Dynamics.Joints.*;
   import Box2D.Collision.b2AABB;
   import Box2D.Collision.Shapes.b2Shape;

   public class AvatarMovement {

      private var m_world:b2World;      
      private var nPhysicsScale:Number;
      private var m_mouseJoint:b2MouseJoint;
      
      private var mouseXWorldPhys:Number;
      private var mouseYWorldPhys:Number;
      private var mouseXWorld:Number;
      private var mouseYWorld:Number;
      
      private var avatar:b2Body;

      public function AvatarMovement(_m_world, listeningSurface:DisplayObject, _m_physScale, _avatar:b2Body)
      {
         avatar = _avatar;
         m_world = _m_world;
         m_physScale = _m_physScale;

         updateMouseWorld();

         if(avatar)
         {
            var md:b2MouseJointDef = new b2MouseJointDef();
            md.body1 = m_world.m_groundBody;
            md.body2 = avatar;
            md.target.Set(mouseXWorldPhys, mouseYWorldPhys);
            md.maxForce = 300.0 * body.m_mass;
            m_mouseJoint = m_world.CreateJoint(md) as b2MouseJoint;
         }
      }

      private function updateMouseWorld():void
      {
         mouseXWorldPhys = mouseX/m_physScale;
         mouseYWorldPhys = mouseY/m_physScale;

         mouseXWorld = mouseX;
         mouseYWorld = mouseY;

         trace(mouseXWorld)
         trace(mouseYWorld)
      }
   }
}
Code:
var body = m_world.CreateBody(bodyDef);


That line returns a reference to the body created. In your original code, you need to use a global variable (bodyAvatar or something) :

Code:
bodyAvatar = m_world.CreateBody(bodyDef);


Then when you instantiate your version of MouseInteraction, pass bodyAvatar as the fourth parameter.


Just a note - the point of MouseInteraction is to attach the body to the mouse without having to deal with event listeners, scaling, etc. If you've removed most of that functionality, then you might as well eschew the extra class, and put the mouse joint creation in your main file, just after the body creation.
Thanks for answering verso.

I'll definitely try that.

I was messing for 12 hours with the code... And in the end I threw it all away and started from scratch. My Main file seemed to contain a bad way of making the graphics. I couldn't even grab them with your file. But now I can now with the new version. 🙂 I guess that a newbie shouldn't try to put a MovieClip skin in straight away, but focus on the shapes and bodies first. I took sample code from many files and tried to glue it all together... apparently not a good idea.

Anyways I learned a lot by messing around your files are really helpful.

I think that I will be able to do it tomorrow... I'll post the results online.

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