2014-11-04 77 views
0

我有一些SKSpriteNode從圖像這樣的: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
-(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]; 
} 
+0

我有這一套,(我編輯的問題),但它仍然會檢測觸摸的角落裏,藍色的形狀是不可見的。 – 2014-11-04 15:31:19

+0

如果你的圖片是PNG。它可以檢測已經是藍色的形狀。 http://en.wikipedia.org/wiki/Portable_Network_Graphics – 2014-11-04 15:37:40

+0

我有png圖像。你可以嘗試它(這是粘貼問題)。它具有透明背景 – 2014-11-04 16:08:52