I m working on a game like Rodents Revenge, just to point out where I m coming from with this question. I m using the cocos2d game engine aswell...
I have a layer that contains about 168 blocks, these blocks are a subclass of a Sprite. Each block contains two instance variables that are integers, one for the xGridLocation and yGridLocation. I have a method that I call that returns an array containing all the blocks that are on the same x or y row as the main character your controlling (the mouse). This method works as long as the blocks stay in the same order (smallest x/y value to largest), but when I start pushing the blocks out of their original row and mixing them up a bit (when playing the game) my logic no longer works because it is based on the fact that the blocks in the array are indexed from smallest to largest based on their xGridLocation or yGridLocation. The xGridLocation and yGridLocation are not based on their position, when the layer first loads they are given preset grid locations and as the block moves in any direction the grid location is changed based on which direction they moved.
My question is how can I go about sorting the array before it s returned in order based on the instance variables xGridLocation or yGridLocation. I was thinking using the sortUsingSelector:@selector(compareValues:) method but wasn t sure how to go about implementing the compareValues method that will do the sorting.
Here is my method I used for getting an array of blocks.
//I have another one for x. The y parameter is the mouses y value.
-(NSMutableArray *)getBlocksForY:(int)y
{
NSMutableArray *blocks = [[NSMutableArray alloc] init];
int tagNum = 0;
//tagNum starts at 0, and goes up to 168, the numer of children (blocks) on
//this layer...
for(tagNum; tagNum<=168; tagNum++)
{
BlueBlock *currentBlock = (BlueBlock *)[self getChildByTag:tagNum];
int currentY = [currentBlock getBlockLocationY];
//Checks to see if the current block has same y value as the mouse, if
//so it adds it to the array.
if(currentY == y)
{
[blocks addObject:currentBlock];
}
}
//I want to sort before returning...
return blocks;
}
If you need more information just ask.