0
votes

I am creating a game using Apple's SpriteKit, and I am wondering what is the most efficient way to find an SKSpriteNode object after creating it.

In one method I initialize a sprite node and assign a name to it:

SKSpriteNode* playerBody = [SKSpriteNode spriteNodeWithImageNamed:@"playerBody.png"];
playerBody.name = @"player";

Later on inside the touchesBegan:withEvent: method I want to find the previously defined sprite node again and store it so I can run actions on it. First I attempted to do this:

SKSpriteNode* body = [self childNodeWithName:@"player"];

However, I have realized that childNodeWithName: is only available in the SKNode class, not SKSpriteNode. So this does not work. What I am thinking now is that I can create an SKNode object and place my SKSpriteNode inside of it. This way I can search for the SKNode using the above method. This seems a bit convoluted, however. Is there a better way?

1

1 Answers

3
votes

SKSpriteNode inherits from SKNode. You can use childNodeWithName.

SKSpriteNode *someSprite = [SKSpriteNode node];

[someSprite childNodeWithName:@"someChildOfSprite"];

Code for comment below asking how to cast SKNode as an SKSpriteNode:

SKSpriteNode *theChildYouWant = (SKSpriteNode*)[someSprite childNodeWithName:@"someChildOfSprite"];