Skip to content

Rotating Canvas Games

Menu
  • Games
    • Balloon Shooter
    • Choozak
    • Polar
    • Tap Shoot Zombie!
    • Speedboat Santa
    • Rapid Car Rush
    • Turtle Leap
    • Crossword
  • HTML5 Games
    • Speedboat Santa HTML5
    • Choozak HTML5
  • Blog
  • Tutorials Index
  • About Us
  • Contact Us
  • Privacy Policy & Terms and Conditions
    • Privacy Policy
    • Terms and Conditions
    • Copyright Notice
    • Disclaimer
Menu

Adding Box2d Object in between a game

Posted on June 24, 2012December 4, 2023 by Rahul Srivastava

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.

  • Tweet
©2025 Rotating Canvas Games | Built using WordPress and Responsive Blogily theme by Superb