来自图像触摸检测的SKSpriteNode

时间:2014-11-04 15:14:40

标签: ios touch sprite-kit shape

我有一些像这样的SKSpriteNode:

enter image description here

当我尝试检测这样的触摸时:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];
    if ([node.name isEqualToString:@"shape"]) {
        NSLog(@"TOUCH DETECT");
    }
}
即使我在角落里触摸外面的蓝色形状,它也会检测到触摸。它采用方形触摸检测。怎么绕过它?我想在蓝色形状内检测触摸。

马尔科

1 个答案:

答案 0 :(得分:1)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];
    if ([node.name isEqualToString:@"shapeMask"]) {
        //Whatever you want.
    }
}
-(void)blueShape{
    SKSpriteNode *blueShape = [SKSpriteNode spriteNodeWithImageNamed:@"blueShape"];
    blueShape.position = yourPosition;
    blueShape.name = @"blueShape";
    [self addChild:blueShape];

    SKShapeNode *shapeMask = [SKShapeNode node];
    shapeMask.name = @"shapeMask";
    CGFloat offsetX = blueShape.frame.size.width * blueShape.anchorPoint.x;
    CGFloat offsetY = blueShape.frame.size.height * blueShape.anchorPoint.y;

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, NULL, 0 - offsetX, 137 - offsetY);
    CGPathAddLineToPoint(path, NULL, 80 - offsetX, 1 - offsetY);
    CGPathAddLineToPoint(path, NULL, 239 - offsetX, 2 - offsetY);
    CGPathAddLineToPoint(path, NULL, 318 - offsetX, 139 - offsetY);
    CGPathAddLineToPoint(path, NULL, 238 - offsetX, 275 - offsetY);
    CGPathAddLineToPoint(path, NULL, 80 - offsetX, 274 - offsetY);
    //Values may not be accurate. You can set yourself with shape tool.
    CGPathCloseSubpath(path);

    [shapeMask setPath:path];
    [blueShape addChild:shapeMask];
}