如何检测物理区域的触摸?

时间:2014-04-29 10:29:19

标签: ios objective-c sprite-kit

我使用此代码创建了SKSpriteNode,而physicsBody则是圆形。我如何检查用户是否在物理实体中触摸过?

self = [super initWithColor:[SKColor clearColor] size:CGSizeMake(200, 200)];
//...
self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.size.width/2.0f];
self.userInteractionEnabled = YES;

2 个答案:

答案 0 :(得分:1)

我确实使用此代码找到了解决问题的方法:

CGMutablePathRef pathRef;
// Fill pathRef with points and create phisycs body using pathRef.

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

    if (CGPathContainsPoint(pathRef, nil, touchLocation, NO)) {
        // If we are here it means user did touche physic body.
    }
}

答案 1 :(得分:0)

最简单的解决方案是使用您需要的尺寸创建第二个不可见的精灵,并将其直接放在您想要记录触摸的区域上。

另一个选项是存储触发有效触摸的所有坐标,并将它们与触摸方法中的实际触摸坐标进行比较,如下所示:

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

    NSLog(@"%@", NSStringFromCGPoint(touchLocation));
    // Compare the touchLocation coordinate against your list of acceptable coordinates...
}