Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
2  
What is wrong with that solution? –  thefourtheye Jan 5 at 2: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 5 at 2: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 5 at 2: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 5 at 2:53
1  
I don't think there is anything special about the fact that you are using the Processing framework. Can we see a use-case? –  Alexander O'Mara Jan 5 at 2:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.