Search code examples
iphonecocos2d-iphoneaccelerometershake

How to detect shake on the iPhone using Cocos2D?


I know how to do shake for the iPhone has been asked a million times on here, but I can't seem to find anything useful regarding the accelerometer with Cocos2D. Everything i have found involves using views and I don't think i am using any views in Cocos2D, if I am they are hidden from me I think. I want to be able to tell when any sort of shake has occured within a CCLayer class?


Solution

  • I figured it out. In the layer class you need to put these lines;

    self.isAccelerometerEnabled = YES;
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1/60];
    shake_once = false;
    

    Then implement this function in the layer class;

    -(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    
    float THRESHOLD = 2;
    
    if (acceleration.x > THRESHOLD || acceleration.x < -THRESHOLD || 
        acceleration.y > THRESHOLD || acceleration.y < -THRESHOLD ||
        acceleration.z > THRESHOLD || acceleration.z < -THRESHOLD) {
    
        if (!shake_once) {
            int derp = 22/7;
            shake_once = true;
        }
    
    }
    else {
        shake_once = false;
    }
    
    }
    

    shake_once is just a boolean to stop one shake from being registered more than once.