拖放具有椭圆形状的SKSpriteNode

时间:2014-06-11 12:59:38

标签: ios objective-c cocoa-touch sprite-kit

我有一个带有一个精灵的场景,用于精灵的图像是一个椭圆形。

Poker chip

我面临的问题是,每当我使用touchAtPoint时,即使触摸发生在图像的透明区域,它也会返回精灵。

我该如何解决?

我目前的代码如下:

-(id)initWithSize:(CGSize)size {

    if (self = [super initWithSize:size]) {

        self.backgroundColor = [SKColor blackColor];
        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
        SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Red"];
        sprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:50.0];
        sprite.physicsBody.affectedByGravity = NO;
        sprite.physicsBody.usesPreciseCollisionDetection = YES;
        [self addChild: sprite];

    }

    return self;
}

- (void)didMoveToView:(SKView *)view {

    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
    [self.view addGestureRecognizer:gestureRecognizer];

}

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {

    if (recognizer.state == UIGestureRecognizerStateBegan) {

        CGPoint touchLocation = [recognizer locationInView:recognizer.view];
        touchLocation = [self convertPointFromView:touchLocation];
        SKNode *touchedNode = (SKNode *)[self nodeAtPoint:touchLocation];
        _selectedNode = touchedNode;

    }
    else if (recognizer.state == UIGestureRecognizerStateChanged) {

        CGPoint translation = [recognizer translationInView:recognizer.view];
        translation = CGPointMake(translation.x, -translation.y);
        [self panForTranslation:translation];
        [recognizer setTranslation:CGPointZero inView:recognizer.view];

    }
}

- (void)panForTranslation:(CGPoint)translation {
    CGPoint position = [_selectedNode position];
    [_selectedNode setPosition:CGPointMake(position.x + translation.x, position.y + translation.y)];
}

1 个答案:

答案 0 :(得分:1)

好的,所以这里唯一相关的代码是......

CGPoint touchLocation = [recognizer locationInView:recognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
SKNode *touchedNode = (SKNode *)[self nodeAtPoint:touchLocation];
_selectedNode = touchedNode;

这需要改为这样......

CGPoint touchLocation = [recognizer locationInView:recognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
SKNode *touchedNode = (SKNode *)[self nodeAtPoint:touchLocation];

// Work out if the touch is inside the circle
CGPoint centerOfNode = CGPointMake(touchedNode.position.x + touchedNode.size.width * 0.5, touchedNode.positiony + touchedNode.size.height * 0.5);

CGFloat dx = touchedNode.position.x - touchLocation.x;
CGFloat dy = touchedNode.position.y - touchLocation.y;

CGFloat distanceFromCenter = sqrtf(dx * dx + dy * dy);

if (distanceFromCenter <= touchedNode.size.width * 0.5) {
    _selectedNode = touchedNode;
}