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: 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.