Search code examples
sprite-kitshakeskscene

Detecting shakes in sprite kit


I have a problem with detecting a shake. It's a skscene in the Sprit Kit and I defined the motion detector like this:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{

}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {

NSLog(@"test?");

}

Where is my mistake? Do I have to implement it like I had to do it with the UIGestureRecognizer?

Thanks in advance (and sorry for my bad english) Julian


Solution

  • Apparently, you can't detect shake events from a SKScene subclass, such as GameScene. However, you can detect them from a view controller, such as GameViewController. When a shake event is triggered, you can call a shake handler in GameScene from the view controller.

    In your GameViewController.m, add this to detect shake events

    - (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        if (motion == UIEventSubtypeMotionShake) {
            SKView *skView = (SKView *)self.view;
            GameScene *scene = (GameScene *)skView.scene;
            // Call a function in the GameScene
            [scene shake];
        }
    }
    

    Add this to the @interface in GameScene.h

    - (void) shake;
    

    Add this to GameScene.m

    - (void) shake {
        NSLog(@"shake");
    }