I am trying to apply a force to a bunch of b2_dynamicBodys, but it seems to only work for a random number of items and then stops with an error.

     //create some items to move
     bodyDef.type = b2Body.b2_dynamicBody;
     for(var i = 0; i < 5; ++i) {
        fixDef.shape = new b2PolygonShape;
        fixDef.friction = 1;
        fixDef.restitution = .1;
        bodyDef.position.x = Math.random() * 10;
        bodyDef.position.y = Math.random() * 10;
        itemsArray.push(world.CreateBody(bodyDef).CreateFixture(fixDef));  // store for later

then i try to apply a force later with:

angle = 20;
for (var xIdx=0; xIdx<itemArray.length; xIdx++) {
    itemsArray[xIdx].GetBody().ApplyImpulse(new b2Vec2(50*Math.cos(angle*Math.PI/180),50*Math.sin(angle*Math.PI/180)););

the error I receive is

TypeError: 'undefined' is not an object (evaluating 'c.x')

Is there something wrong with saving the items for later use when I am creating them? Does anyone know what is causing this.


1 Answer 1


Is diceArray.length used in this code:

for (var xIdx=0; xIdx<diceArray.length; xIdx++) {

the same as itemsArray.length when referencing itemsArray in the same loop?


So, itemsArray size is definitely 5, is diceArray size 5 too?

Edited now jfiddle source given: ApplyImpulse requires 2 parameters and you are only passing in 1.

I added {x:200,y:200} and all is fine

diceArray[xIdx].GetBody().ApplyImpulse(actionVec, {x:200,y:200});
  • \$\begingroup\$ sorry typo, yes they are the same. I renamed the array. jsfiddle.net/nycynik/LGq63 \$\endgroup\$
    – nycynik
    Commented Nov 3, 2012 at 15:40
  • \$\begingroup\$ after adding that fiddle, i think i see that it never works, its not random at all. \$\endgroup\$
    – nycynik
    Commented Nov 3, 2012 at 15:43
  • \$\begingroup\$ See edit above for solution \$\endgroup\$
    – John
    Commented Nov 3, 2012 at 15:54
  • \$\begingroup\$ Oh! Yes it does public function ApplyImpulse(impulse:b2Vec2,point:b2Vec2):voidParameters The point is the origin of the force. Thank you! \$\endgroup\$
    – nycynik
    Commented Nov 3, 2012 at 16:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .