Question

I have following simple code:

//
//  BGMyScene.m
//  Test1
//
//  Created by AndrewShmig on 3/10/14.
//  Copyright (c) 2014 Bleeding Games. All rights reserved.
//

#import "BGMyScene.h"

@implementation BGMyScene

- (id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */

        self.backgroundColor = [SKColor colorWithRed:0.15
                                               green:0.15
                                                blue:0.3
                                               alpha:1.0];

//      first label
        SKLabelNode *myLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
//        myLabel.userInteractionEnabled = YES;
        myLabel.text = @"Hello, World!";
        myLabel.fontSize = 30;
        myLabel.position = CGPointMake(CGRectGetMidX(self.frame),
                                       CGRectGetMidY(self.frame));
        [self addChild:myLabel];

//      second label
        SKLabelNode *myLabel2 = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        // myLabel2.userInteractionEnabled = YES;
        myLabel2.text = @"Hello, World!";
        myLabel2.fontSize = 30;
        myLabel2.position = CGPointMake(100, 100);
        [self addChild:myLabel2];
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self];
    SKNode *touchedNode = [self nodeAtPoint:touchLocation];

    NSLog(@"touchLocation x: %f and y: %f", touchLocation.x, touchLocation.y);

    if (touchedNode != self) {
        NSLog(@"Removed from parent.");
        [touchedNode removeFromParent];
    }
}

- (void)update:(CFTimeInterval)currentTime
{
    /* Called before each frame is rendered */
}

@end

What it does is creating two SKLabelNodes and checks if that labels were touched, if yes - remove them from parent node.

The strange thing is that when I set userInteractionEnabled to YES SKLabelNode won't receive any touch event. Leaving userInteractionEnabled to NO works fine.

Maybe its better to name this property userInteractionDisabled? Am I missing something about it?

Was it helpful?

Solution

Your code is working as I expect it would.

As far as I can see it is not the SKLabelNodes receiving touches but the SKScene which has the -(void)touchesBegan... This means that if you add the SKLabelNodes and set them to .userInteractionEnabled = YES then they will soak up the touches before they reach the scene, because they're on top of the scene.

Otherwise you should subclass SKLabelNode and set userInteractionEnabled in your custom initialiser. And then have the touchesBegan in the subclass of the SKLabelNode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top