Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIPanGestureRecognizer in SKScene

I've been experimenting with UIGestureRecognizers and the new SKScene/SKNode's in SpriteKit. I've had one problem, and I got close to fixing it but I am confused on one thing. Essentially, I have a pan gesture recognizer that allows the user to drag a sprite on the screen.

The single problem I have is that it takes ONE tap to actually initialize the pan gesture, and then only on the SECOND tap on it works correctly. I'm thinking that this is because my pan gesture is initialized in touchesBegan. However, I don't know where else to put it since initializing it in the SKScene's initWithSize method stopped the gesture recognizer from actually working.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    if (!self.pan) {

        self.pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(dragPlayer:)];
        self.pan.minimumNumberOfTouches = 1;
        self.pan.delegate = self;
        [self.view addGestureRecognizer:self.pan];
    }
}

-(void)dragPlayer: (UIPanGestureRecognizer *)gesture {

        CGPoint trans = [gesture translationInView:self.view];

        SKAction *moveAction =  [SKAction moveByX:trans.x y:-trans.y  duration:0];
        [self.player runAction:move];

        [gesture setTranslation:CGPointMake(0, 0) inView:self.view];
    }
like image 653
EvilAegis Avatar asked Sep 26 '13 23:09

EvilAegis


1 Answers

That's because you're adding the gesture in touches began, so the gesture doesn't exist until the screen has been tapped at least once. Additionally, I would verify that you're actually using initWithSize: as your initializer, because you shouldn't have any problems adding the gesture there.

Another option is to move the code to add the gesture into -[SKScene didMovetoView:] which gets called immediately after the scene has been presented. More info in the docs.

- (void)didMoveToView:(SKView *)view
{
    [super didMoveToView:view];
    // add gesture here!
}
like image 143
Mick MacCallum Avatar answered Sep 22 '22 20:09

Mick MacCallum