简体   繁体   English

如何在PhysicsBody区域中检测触摸?

[英]How to detect touches in physicsBody area?

I did create SKSpriteNode using this code and physicsBody is circle. 我确实使用此代码创建了SKSpriteNode,而physicsBody是圆形的。 How I could check that user did touch eare in the physicsBody? 我如何检查用户是否在PhysicsBody中触摸耳朵?

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

I did found solution for my problem using this code: 我确实使用以下代码找到了解决问题的方法:

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.
    }
}

The easiest solution would be to create a second invisible sprite, with the size you need, and place it directly over the area you want to record touches on. 最简单的解决方案是创建第二个不可见的精灵,它具有所需的大小,并将其直接放在要记录触摸的区域上。

The other option is to store ALL the coordinates which trigger a valid touch and compare them against the actual touch coordinate in your touch method, like this: 另一个选择是存储所有触发有效触摸的坐标,并将它们与您的触摸方法中的实际触摸坐标进行比较,如下所示:

-(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...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM