Ryan Earnshaw
Ryan Earnshaw

Reputation: 37

Move all objects in an array - IOS and Sprite Kit

So here is what I am trying to achieve;

I am trying to create a tile map system. So when the player presses the up button for example, the player stays central and the map moves down to give the look that the player is walking up the world (its a top-down game).

I have created an array of SpriteNode's and a function that creates 64x64 tiles and adds each new object to the array. I am trying to figure out a way that I can apply a function to all of the tiles.

So for example, when the up button is pressed all the tiles start to move down.

I could do this manually:

SpriteNode *tile00;
SpriteNode *tile01;
SpriteNode *tile02;
...

and then change the position of each one manually when the player moves but this is going to be very tedious (especially considering that I plan to create rather large maps)

My Question: Can I apply functions to several SpriteNodes?

Upvotes: 0

Views: 261

Answers (2)

Chris Loonam
Chris Loonam

Reputation: 5745

If you have an NSArray of tile sprites, applying an action to all of them could be done like this

SKAction *moveAction = //move all tiles down, up, etc.;
for (SKSpriteNode *tile in self.tiles) /* an NSArray containing the tile sprites */
{
    [tile runAction:moveAction];
}

Upvotes: 1

Wyetro
Wyetro

Reputation: 8588

You should definitely create functions:

- (void) moveUp {
// Loop through array of nodes and move them down
}
- (void) moveDown {
// Loop through array of nodes and move them up
}
- (void) moveRight {
// Loop through array of nodes and move them left
}
- (void) moveLeft {
// Loop through array of nodes and move them right
}

You can loop through the nodes if you create an NSArray of nodes and do this:

for (SKSpriteNode *n in NodeArray){ // NodeArray is you NSArray
// Do something to n
}

Upvotes: 1

Related Questions