I'm building a little game in Processing's Javascript mode and have my enemies as objects in an array. I'd like to sort them by their Y coordinate to draw them in vertical order (and not overlap and look weird). Since they are generated and respawned over the course of the game, I need to sort this array repeatedly.
I've done this before in the regular Java mode using Arrays.sort()
and Comparable
, but that doesn't work in JS mode.
Any ideas? I found this suggestion but can't figure out how to implement it:
enemies.sort(function(a,b) { return parseFloat(a.yPos) - parseFloat(b.yPos) } );
EDIT
As requested, here's a bit more context:
Enemy[] enemies = new Enemy[10];
void setup() {
for (int i=0; i<10; i++) {
enemies[i] = new Enemy();
}
enemies.sort(function(a,b) { return parseFloat(a.yPos) - parseFloat(b.yPos) } );
}
class Enemy {
float xPos, yPos;
Enemy() {
xPos = random(0,width);
yPos = random(0,height);
}
}
This throws an error on the sort
line: unexpected token: {
.
I know one can mix pure JS within Processing JS, but in this case it doesn't work and I don't know why.