In learning SpriteKit, I am trying to make a small adventure game. I am creating a hero, and adding it to the scene, and then later, during touchesBegan:
, I detect if the touch originated on the hero, and take actions accordingly.
If I add the hero as a SKSpriteNode
the touch detects him. If I add him as a subclass of SKSpriteNode
the touch does not! The difference in adding:
_heroNode = [SKSpriteNode spriteNodeWithImageNamed:@"hero.png"];
vs
_heroNode = [[ADVHeroNode alloc] init];
The init looks like this:
- (id) init {
if (self = [super init]) {
self.name = @"heroNode";
SKSpriteNode *image = [SKSpriteNode spriteNodeWithImageNamed:@"hero.png"];
[self addChild:image];
}
return self;
}
Adding the hero as a subclass of SKSpriteNode works in the sense that it is added to the scene, but the touch doesn't detect him. My touchesBegan:
looks like this:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if (YES) NSLog(@"Node name where touch began: %@", node.name);
//if hero touched set BOOL
if ([node.name isEqualToString:@"heroNode"]) {
if (YES) NSLog(@"touch in hero");
touchedHero = YES;
}
}
Frustratingly, this code works just fine when adding a straight up SKSpriteNode
, and not my own subclass of it. Any suggestions?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…