Projectiles in a video game

Started by
2 comments, last by LAURENT* 9 years, 3 months ago

Is it smart to allocate memory for every projectile and delete the memory when it collides with something? If not, how would you try this? I don't do dynamic memory allocation often so I just asking for the approach.

Advertisement
http://en.wikipedia.org/wiki/Object_pool_pattern

As Nypyren linked, it's really good to use an object pool. Projectiles and particle systems can create lots of short-lifetime objects that are constantly going in and out of existence. Dynamic memory allocation is actually pretty expensive compared to logic and math. It takes time for the requested memory to be allocated and handed back to you, and over time lots of dynamic memory allocation can cause memory fragmentation. Fragmented memory slows things down because memory relevant to an algorithm is spread out through the memory in random locations. It is faster to read through contiguous memory in a straight line, or nearby memory, than to jump around between random memory addresses. Pool allocation is awesome for cache coherency because you can allocate the space for many objects at one time, which puts them close together in memory. It's faster than dynamic allocation because your pool can immediately hand you back an object that was already allocated. Memory allocators are a pretty fun topic with a lot of internet resources.

The best idea would be to write a pool to hold your projectiles. When a bullet is shot you grab an object from the pool, and when it hits something you return that object to the pool to be reused later. Done correctly there will be no allocation/deallocation to slow the processing of your bullets down.

Oh thank you so much. My worries about slow down are put to rest. This looks way better than allocating.

This topic is closed to new replies.

Advertisement