Search code examples
xna2dcollision-detectioncollision

How to share collision layer to every objects?


Currently, each level has 3 layers :

  • background
  • collisions(walls, invisible walls, ground, etc)
  • foreground

My character sprite has 1 pixel to detect the collision. In this character class, there is a Color[] contains every pixels of the collision layer.

I calculate the position of the Character's pixel detection, and obtain an int that i can use with the Color[] ("CharactersPixel")

if ( Color[CharactersPixel].A != 0 )
    Then collision.

It works perfectly.

But the collision layer has to be used by every others objects like particles, monsters etc.

The collision layer has about 3.800.000 pixels. so the Color[] has the same.

If I add this Color[] to every objects, this will use too much RAM, right ?


Solution

  • You'd only add a reference to your collision layer to the objects. You are not copying the entire thing to each object. Adding a reference will not add much memory to your objects.

    However, I would suggest making the collision available in some more general fashion by exposing some level data in a place accessible to any object. Perhaps you could add the data to your Game class as a property CurrentLevel with CollisionData as an accessible property.

    Normally you keep the collision data separate from the actual rendering colours, and perform a more simplistic collision with boxes and the like instead that approximately match the shape of the collision data. This would in the end make it easier to calculate things like the angle which you impact the environment and calculation of appropriate physics. Pixel to pixel collisions are rare, and might also be problematic from a performance perspective.