Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What best represents a character SKNode or SKSpriteNode?

Tags:

ios

sprite-kit

enter image description hereCurrenty, my class looks something like

@interface Character : SKNode

@property (nonatomic, assign) CGFloat walkingSpeed;

@implementation Character

+(Character*)characterWithLevel:(BaseLevel *)level {
  return [[self alloc] initWithLevel:level];
}

-(id)initWithLevel:(BaseLevel*)level {

    if (self = [super init]) {
        _sprite = [SKSpriteNode spriteNodeWithImageNamed:level.heroTexture];
        _sprite.position = level.heroStartingPosition;

        [self addChild:_sprite];
        [level addChild:self];
    }

    return self;
}

Problem is, when running actions against a Character node in the level, it simple won't do anything due to the fact that the SpriteNode is the one being animated. I'm wondering how would you guys approach these kind of problems?

Example of action:

On touch event:

CGPoint location = [[touches anyObject] locationInNode:self];
[character moveToPosition:location];

Inside Character class

-(void)move {
    [self runAction:[SKAction repeatActionForever:[SKAction animateWithTextures:[self walkFrames]
                                                                   timePerFrame:0.1f
                                                                         resize:NO
                                                                        restore:YES]] withKey:@"moving"];
    return;
}

This doesn't do anything. Only way I can get it to work is if Character was a subclass of SKSpriteNode. Running the action against self.sprite also seems kind of hacky and the node itself won't move.

Any suggestions?

like image 442
MrShoot Avatar asked Nov 07 '13 21:11

MrShoot


1 Answers

Why does using self.sprite seem hacky? It's perfectly valid.

In fact, from an OOP point of view, the SKNode aggregating other visible nodes is the more versatile approach.

For example it would allow you to hide the sprite and instead make a particle emitter visible if the player picked up a powerup that makes him invisible (or very transparent) with just a few sparkly bits around him.

To achieve that, you would have an emitter as child of the character node. If the character node where the player sprite, you couldn't turn just the sprite invisible because this would also affect the child emitter.

Therefore in the long run it's better to aggregate views (visible nodes) rather than subclassing them. Think of the Character SKNode as the view controller for one or more views (its children like sprites, emitters, labels, etc).

like image 70
LearnCocos2D Avatar answered Sep 18 '22 02:09

LearnCocos2D