Loading...
Logo
Processing Forum
hi guys,

I'm currently working on a simple 2D shooter game. Basically, there's one instance of my player-class and 50 instances of my creep-class on the map. They change position every loop. Something like this:

class Creep {

      float x;
      float y;
      PImage sprite;
      ...

}

I need to find a way to sort all those instances depending on their Y-position before they are being drawn to the window, so that they're overlapping correctly! e.g. there's creep_a at y=5 and another creep_b at y=6. the game has to draw creep_a first, so that creep_b appears to be in front of it!

My first thought was to create an arrayList for all moving objects (player and creeps), which is then sorted by comparing every Y-position. But no matter how hard I try, I can't find a way to make it work.

I hope you guys understand what my problem is (and excuse my poor english)
Please let me know how you would solve that problem!

thank you,
Al



Replies(3)

Since you already have a class for your creep then you can make the class comparable, this then lets you to perform a very simple sort before you draw them

class Creep implements Comparable {

      float x;
      float y;
      PImage sprite;
      ...

    public int compareTo(Object o) {
      Creep c = (Creep) o;
      if(y == o.y)
         return 0; // zero
            if(y < o.y)
                  return -1;
            else
                  return 1;
    }

}
// end of class Creep

To sort the creeps depends on what you use to store them.

If you have an ArrayList or LinkedList of Creep called creeps then use
Collections.sort(creeps);

if they are in an array then use
Arrays.sort(creeps);

Thanks for the quick reply!
Will try it this way :)
IT WORKS!!

Thank you very much, it was easier than I had expected! :)