Adding Box2d Object in between a game

Hi,

In our one of the previous post about adding box2d objects in game we created all the box2d bodies in the initialization phase and during the game we were just making the sensor objects (removing their collision response) so that they acted as if they were not present. We added a custom flag to check if the body is alive or dead and depending on that we added collision response.

Now if we want to create a box2d body while the game is running then we have to make sure we call it after world.step command is executed in update function. For e.g. there is a cannon which shoots every 3 seconds and we want to create a box2d object each time it shoots and destroy it on hitting another object. In that case one way to do it is make an ArrayList which holds all the objects to be added  and in the update function, create objects in the list and clear the list after the world.step command. Lets just create a simple class which holds information which can be used to create a box2d object.

public BoxObjectInfo{
       public float x,y;
       public float width,height;
       //Other properties.
}

Now Assuming another class which handles all the box2d bodies.

public BoxManager(){
     //......

     ArrayList<BoxObjectInfo> toAdd;
     public void Update(float dt){
        //Update Box2d World
        world.step(dt,velocityIteration,positionIteration);
         for(BoxObjectInfo inf:toAdd){
                 CreateBodyFromInfo(inf);
         }
         toAdd.clear();
     } 

      void CreateBodyFromInfo(BoxObjectInfo inf){
             //Create the body in similar way as you did during initialization.
      } 
}

This is important in a way because if you try to add a box2d object for example in collision response functions of ContactListener interface then most of the time you would get an error like “Assertion failed: (IsLocked() == false)“. So to avoid that for adding and deleting a box2d object put them in an array and after world.step is executed then add/delete the objects in the array and clear the arrays.

Hope this helps who may have got stuck in this problem. If you have any queries please post them in comments section. Thanks.

Tagged with: , , ,
Posted in Tutorials
Try our games



Error: Twitter did not respond. Please wait a few minutes and refresh this page.