触摸期间未检测到自定义SKSpriteNode

zee*_*ple 12 ios sprite-kit

在学习SpriteKit时,我正在尝试制作一款小型冒险游戏.我正在创建一个英雄,并将其添加到场景中,然后,在此期间touchesBegan:,我检测到触摸是否源自英雄,并相应地采取行动.

如果我添加英雄作为SKSpriteNode触摸检测他.如果我把他添加为SKSpriteNode触摸的子类不!添加的区别:

_heroNode = [SKSpriteNode spriteNodeWithImageNamed:@"hero.png"];
Run Code Online (Sandbox Code Playgroud)

VS

_heroNode = [[ADVHeroNode alloc] init];
Run Code Online (Sandbox Code Playgroud)

init看起来像这样:

- (id) init {
    if (self = [super init]) {

        self.name = @"heroNode";
        SKSpriteNode *image = [SKSpriteNode spriteNodeWithImageNamed:@"hero.png"];
        [self addChild:image];
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

将英雄添加为SKSpriteNode的子类可以将其添加到场景中,但触摸不会检测到他.我touchesBegan:看起来像这样:

-(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;
    }
}
Run Code Online (Sandbox Code Playgroud)

令人沮丧的是,这个代码在添加一个直接的时候工作得很好SKSpriteNode,而不是我自己的子类.有什么建议?

Dog*_*fee 24

以下是一些子类化Hero的示例方法

SKNode

子类化SKNode此方法需要您的节点监视触摸,因此需要self.userInteractionEnabled属性.

@implementation HeroSprite

- (id) init {
    if (self = [super init]) {
        [self setUpHeroDetails];
        self.userInteractionEnabled = YES;
    }
    return self;
}

-(void) setUpHeroDetails
{
    self.name = @"heroNode";
    SKSpriteNode *heroImage = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
    [self addChild:heroImage];
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint locationA = [touch locationInNode:self];
    CGPoint locationB = [touch locationInNode:self.parent];
    NSLog(@"Hit at, %@ %@", NSStringFromCGPoint(locationA), NSStringFromCGPoint(locationB));
}

@end
Run Code Online (Sandbox Code Playgroud)

SKSpriteNode

另一种"更简单"的方式,如果你只是想要子类化SKSpriteNode.这将基本上与您使用的相同(在您想要继承您的Hero之前).所以你的touchesBegan,在你的问题中设置将起作用.

@implementation HeroSprite

- (id) init {
    if (self = [super init]) {
        self = [HeroSprite spriteNodeWithImageNamed:@"Spaceship"];
        [self setUpHeroDetails];

    }
    return self;
}

-(void) setUpHeroDetails {
    self.name = @"heroNode";
}

@end
Run Code Online (Sandbox Code Playgroud)


Faw*_*kes 10

请务必在init方法中添加它.

self.userInteractionEnabled = YES;
Run Code Online (Sandbox Code Playgroud)

由于某些原因,在子类化时默认情况下不启用此选项.至少对我来说,它只在手动启用时才有效.