Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 1 down vote accepted

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});
share|improve this answer
sorry typo, yes they are the same. I renamed the array. – nycynik Nov 3 '12 at 15:40
after adding that fiddle, i think i see that it never works, its not random at all. – nycynik Nov 3 '12 at 15:43
See edit above for solution – John Nov 3 '12 at 15:54
Oh! Yes it does public function ApplyImpulse(impulse:b2Vec2,point:b2Vec2):voidParameters The point is the origin of the force. Thank you! – nycynik Nov 3 '12 at 16:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.