Sign in to follow this  
LAURENT*

Projectiles in a video game

Recommended Posts

LAURENT*    779

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.

Edited by LAURENT*

Share this post


Link to post
Share on other sites
BrentMorris    1225

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.

Edited by DementedCarrot

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this