TAGS :Viewed: 11 - Published at: a few seconds ago

[ Increase region where SKNode can be pressed ]

I'm wondering if there's an easy way that I could take an SKNode and increase the region in which it is pressed.

For example, I am currently checking if a node is clicked like so:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
   UITouch *touch = [touches anyObject];
   CGPoint positionInScene = [touch locationInNode:self];
   SKNode *node = [self nodeAtPoint:positionInScene];
   if ([node.name isEqualToString:TARGET_NAME]) {
       // do whatever

If the node drawn on the screen is something like 40 pixels by 40 pixels, is there a way that if a user clicks within 10 pixels of the node, it would render as being clicked?


Answer 1

You could add an invisible sprite node as a child to the visible node. Have the child node's size be larger than the visible node's.

For example, on OSX this would work in a scene:

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        SKSpriteNode *visibleNode = [[SKSpriteNode alloc] initWithColor:[NSColor yellowColor] size:CGSizeMake(100, 100)];
        visibleNode.name = @"visible node";
        visibleNode.position = CGPointMake(320, 240);

        SKSpriteNode *clickableNode = [[SKSpriteNode alloc] init];
        clickableNode.size = CGSizeMake(200, 200);
        clickableNode.name = @"clickable node";

        [visibleNode addChild:clickableNode];
        [self addChild:visibleNode];
    return self;

-(void)mouseDown:(NSEvent *)theEvent
    CGPoint positionInScene = [theEvent locationInNode:self];
    SKNode *node = [self nodeAtPoint:positionInScene];
    NSLog(@"Clicked node: %@", node.name);

The clickable node extends 50px outwards from the edges of the visible node. Clicking within this will output "Clicked node: clickable node".

The node named "visible node" will never be returned by the call to [self nodeAtPoint:positionInScene], because the clickable node overlays it.

The same principle applies on iOS.