Monday 10 June 2013

Optimizing performance in CitrusEngine and Box2D

Performance tips.

I will explain my experience when I was building Beekyr game for AIR using CitrusEngine and Box2D....

This might be applied to other game engines.... but the way Box2D is used might be the same.
When I created first Beekyr stage prototype I had about 2000 objects moving smoothly in screen, Stage3D was just amazing. But I needed the sprites to collide between each other. Everyone recommended to use the physics engine Box2D, even it if was just for collisions (later on I replaced it for Nape engine (for AS3), which is at least twice as fast, click here to see how I converted from Box2D to Nape).

After adding the physics engine, I only was able to have about hundred of objects moving smooth and fast (still no code to make them react with each other).

I didn't realize that a physics engine would make things THAT slow, specially in smartphones, so I had to start optimizing everything:
I made everything to be classified as sensor:
_fixtureDef.isSensor = true;
That means that touching objects can overlap without having a bounce effect or something.

Enable only begin handle contact:
beginContactEnabled = true;
Objects will not react until I enabled at least one form of contact in Citurs Engine.
Then I want to create groups, that means groups with the same ID will not react to each other this is very good when you have loads of real bullets or lots of enemies, this will stop most collision functions to be triggered when the bullets or enemies overlap.
The way to do this is to edit the fixture filter, this is how enemy bodies are filtered:
    override protected function defineFixture():void {
           super.defineFixture();
           _fixtureDef.filter.groupIndex = GameVars.ENEMY_GROUP;
           _fixtureDef.isSensor = true;
        }

Don't ever use isBullet() unless is completelly necesary. This will add more calculations to the engine making it slower.



No comments: