简体   繁体   中英

How to detect touches in physicsBody area?

I did create SKSpriteNode using this code and physicsBody is circle. How I could check that user did touch eare in the 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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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