Best way for particles?

Hi,
Im implementing an experimental verson of CRobots in java, my own style (yes i know there is a JRobots ::slight_smile: ) Well I need a particle engine, in working in Java2D 1.5. Is the best way to use small images? or pixels? How do
I avoid creating new objects on the heap?

Best way is to use small images.

As for reducing heap allocations:

  1. Don’t bother. It probably won’t gain you anything.

  2. Object pool:


class myClass
{
    static myClass freeList = null;
    myClass next = null;

    myClass Alloc()
    {
                          if(freeList != null)
                          {
                                       myClass ret = freeList;
                                       freeList = ret.next;
                                       ret.next = null;
                                       return ret;
                          }
                          return new myClass;
    }
    void Free()
    {
                          next = freeList;
                          freeList = this;
    }
}

Then call ‘Alloc’ when you need a new object - but remember to call ‘Free’ when you have finished with it, and be prepared to track down leaks etc.

Awsome code!
And I was killing my self how to create a list
for particles that does reuse objects. =)
Thanks!

Ill add an “active” static member to so I know which particles to draw.

Yep. then adjust the code so an allocated one is automatically tagged onto the active list and away you go :slight_smile:

Another method is to allocate a fixed array of ‘maxParticles’ and a counter for how many are used. When one ‘expires’, you just swap the reference to the last active and the expired one in the array and decrease the counter by one. This way, nothing needs ‘sorting’, the active ones are always at the start of the array, and nothing needs allocating/deallocating again.

However - it is worth noting that with Java these may actually make the code slower & more complicated, as the GCs have come a long way in recent versions.