0

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.

Community
  • 1
  • 1
JeffThompson
  • 1,538
  • 3
  • 24
  • 47
  • 2
    What is wrong with that solution? – thefourtheye Jan 05 '14 at 02:48
  • 1
    Assuming `enemies` refers to an array of objects that each have a `yPos` property that should work. (Although you don't need the `parseFloat()`, you can use `return a.yPos - b.yPos;`.) – nnnnnn Jan 05 '14 at 02:49
  • To clarify - that code above might well work, I just don't know how to use it within the Processing JS framework. – JeffThompson Jan 05 '14 at 02:51
  • What do you mean by Processing JS framework? Please show us a piece of code where this code doesn't produce expected result. – thefourtheye Jan 05 '14 at 02:53
  • @JeffThompson "To clarify - that code above might well work, I just don't know how to use it within the Processing JS framework." Copy, paste. – bjb568 Jan 05 '14 at 03:13

0 Answers0