How to use ApplyForce with box2DWeb

75 views Asked by At

I have a Box2DWeb sketch working ok but I am unable to figure out how to use the ApplyForce method with a body. I have attached the working codepen. On line 85, I have commented out the line that I thought would work but everything disappears when I include it.

If anyone could let me know the correct way to use it, I would be very happy. I have RTFM and seen similar posts on StackO but I still cannot work it out.

http://codepen.io/anon/pen/vOJByN?editors=101

Thanks a lot,

Steven

// single dynamic object----------------------
  var fixDef2 = new b2FixtureDef;
  fixDef2.density = 1.0
  fixDef2.friction = 0.2;
  fixDef2.restitution = 0.5;

  var bodyDef2 = new b2BodyDef;
  bodyDef2.type = b2Body.b2_dynamicBody;

  fixDef2.shape = new b2PolygonShape;
  fixDef2.shape.SetAsBox((300/SCALE)/2, (60/SCALE) / 2);

  bodyDef2.position.x = canvas.width/4/SCALE;
  bodyDef2.position.y = canvas.height/2/SCALE;
  bodyDef2.angle = 5;

  world.CreateBody(bodyDef2).CreateFixture(fixDef2);

// Apply force to object----------------------
/*bodyDef2.ApplyForce(new b2Vec2(500,50) , bodyDef2.GetWorldCenter());
*/
1

There are 1 answers

0
Ilya Tikhonov On

You should call ApplyForce method of b2Body, not of b2BodyDef. You can get b2Body object as result of world.CreateBody(bodyDef2) method.

I've changed your codepen here: http://codepen.io/anon/pen/NqZvqG

Your code:

world.CreateBody(bodyDef2).CreateFixture(fixDef2);

// Apply force to object----------------------
/*bodyDef2.ApplyForce(new b2Vec2(500,50) , bodyDef2.GetWorldCenter());
*/

My code:

var myBody = world.CreateBody(bodyDef2);
var myFixture = mybody.CreateFixture(fixDef2);

// Apply force to object
myBody.ApplyForce(new b2Vec2(500,50), myBody.GetWorldCenter());