Custom SKSpriteNode not detected during touch

前端 未结 5 790
一整个雨季
一整个雨季 2020-12-15 09:06

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 det

5条回答
  •  既然无缘
    2020-12-15 10:12

    Here are some example ways to subclass your Hero

    SKNode

    Subclass an SKNode this method requires your node to monitor for touches, hence the self.userInteractionEnabled property.

    @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
    

    SKSpriteNode

    The other "easier" way, if you just want to subclass a SKSpriteNode. This will work essentially the same as you are use to (before you wanted to subclass your Hero). So your touchesBegan, as set up in your question will work.

    @implementation HeroSprite
    
    - (id) init {
        if (self = [super init]) {
            self = [HeroSprite spriteNodeWithImageNamed:@"Spaceship"];
            [self setUpHeroDetails];
    
        }
        return self;
    }
    
    -(void) setUpHeroDetails {
        self.name = @"heroNode";
    }
    
    @end
    

提交回复
热议问题