Search code examples
c#xnafarseer2d-games

Should I try to amalgamate static bodies as much as possible?


Im making a roguelike game, using XNA and farseer physics. Some rooms will have a procedurally generated cave like layout made from blocks. "caves" with farseer debug mode on

At the moment every block is a seperate body. created thusly:

 _floor = BodyFactory.CreateRectangle(_world,   ConvertUnits.ToSimUnits(Globals.SmallGridSize.X), ConvertUnits.ToSimUnits(Globals.SmallGridSize.Y), 30f);
        _floor.Position = ConvertUnits.ToSimUnits(_position.X + _centerVect.X, _position.Y + _centerVect.Y);
        _floor.IsStatic = true;
        _floor.Restitution = 0.2f;
        _floor.Friction = 0.2f;

Should I Just have one body per room and add all the rectangle shapes for each block to the body? Will this give me a performance boost? Also will it be possible to add and remove block shapes to this body (in order to be able to destroy a block and then "add" the exposed one behind it)?


Solution

  • You will most likely want to retain having 1 Body per block, as it will be a lot easier for you to manage collisions when destroying a block. Consider having to recalculate the shape of the 1 Body after a block is destroyed. This would be quite taxing.

    This is very similar to a game I have abandoned. I originally had a Body for each block, which was very slow:

    http://www.jgallant.com/images/uranus/land2.png

    My first optimization was only setting Bodies on the edge of the generated world:

    http://www.jgallant.com/images/uranus/chunk.png

    This led to faster code, but there was still a problem with having too many bodies on screen. My later optimizations added Bodies to the edges based on where the player was located on the world. Bodies were pulled from a Pool of available bodies, and moved to the proper location. Bodies were never destroyed, simply moved to Vector2(Int.Min, Int.Min) when not used. When they needed to be used, they were moved to position:

    http://www.jgallant.com/images/collision2.jpg

    This provided the fastest code from the three methods. If you are looking to destroy/create bodies on the fly, this is a really bad idea. You are better off storing available bodies in a pool, and re-using them.

    There are some complexities to this also. I do not have my code handy at the moment, but if you have extra questions, I can post some of my code to help out.