Why does creating dynamic bodies in JBox2D freeze my app?

Posted by Amplify91 on Game Development See other posts from Game Development or by Amplify91
Published on 2012-05-03T19:45:50Z Indexed on 2012/06/09 4:47 UTC
Read the original article Hit count: 278

Filed under:
|
|
|

My game hangs/freezes when I create dynamic bullet objects with Box2D and I don't know why. I am making a game where the main character can shoot bullets by the user tapping on the screen. Each touch event spawns a new FireProjectileEvent that is handled properly by an event queue. So I know my problem is not trying to create a new body while the box2d world is locked. My bullets are then created and managed by an object pool class like this:

public Projectile getProjectile(){
    for(int i=0;i<mProjectiles.size();i++){
        if(!mProjectiles.get(i).isActive){
            return mProjectiles.get(i);
        }
    }

    return mSpriteFactory.createProjectile();

}

mSpriteFactory.createProjectile() leads to the physics component of the Projectile class creating its box2d body. I have narrowed the issue down to this method and it looks like this:

public void create(World world, float x, float y, Vec2 vertices[], boolean dynamic){

    BodyDef bodyDef = new BodyDef();
    if(dynamic){
        bodyDef.type = BodyType.DYNAMIC;
    }else{
        bodyDef.type = BodyType.STATIC;
    }
    bodyDef.position.set(x, y);
    mBody = world.createBody(bodyDef);

    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.set(vertices, vertices.length);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.0f;
    mBody.createFixture(fixtureDef);
    mBody.setFixedRotation(true);

}

If the dynamic parameter is set to true my game freezes before crashing, but if it is false, it will create a projectile exactly how I want it just doesn't function properly (because a projectile is not a static object). Why does my program fail when I try to create a dynamic object at runtime but not when I create a static one? I have other dynamic objects (like my main character) that work fine. Any help would be greatly appreciated.

This is a screenshot of a method profile I did: enter image description here Especially notable is number 8. I'm just still unsure what I'm doing wrong.

Other notes:
I am using JBox2D 2.1.2.2. (Upgraded from 2.1.2.1 to try to fix this problem)
When the application freezes, if I hit the back button, it appears to move my game backwards by one update tick. Very strange.

© Game Development or respective owner

Related posts about java

Related posts about android