zdd
zdd

Reputation: 8757

How to use accelerometer in cocos2d 3.0?

I am programming with Cocos2d 3.0 now, In Cocos2d 2.0, we can use the following code to add accelerometer to app, but this example was based on class CCLayer which has deprecate in Cocos2d 3.0, and UIAccelerometer also replaced by CMMotionManager in IOS 5.0, so I am wondering how to do this in Cocos2d 3.0? I googled for a while, didn't find anything useful.

-(id) init
{
    if ((self = [super init]))
    {
        // ...
        self.isAccelerometerEnabled = YES;
        // ...
    }
}

-(void) accelerometer:(UIAccelerometer *)accelerometer 
        didAccelerate:(UIAcceleration *)acceleration
{
    // ...
}

===

Upvotes: 2

Views: 1908

Answers (3)

Dmytro
Dmytro

Reputation: 1390

Here is example:

Device::setAccelerometerEnabled(true);
auto accelerometerListener = EventListenerAcceleration::create([this](Acceleration* acc, Event* event)
{
});

getEventDispatcher()->addEventListenerWithSceneGraphPriority(accelerometerListener, this);

Also video tutorial https://www.youtube.com/watch?v=Xk6lXK6trxU

Upvotes: 1

Sauvik Dolui
Sauvik Dolui

Reputation: 5660

Well, there are two problems in the tutorial example given above.

  1. Single instance of CMMotionManager.
  2. Acceleration data become +Ve or -Ve according to the orientation of the device. You also need to add Scene as observer of device orientation change notification.

If you don't want handle these overheads, you can use CCAccelerometer class. It solves both the problems.

HOW TO USE

  1. Add CoreMotion Framework in your project from Build Phases.
  2. Copy CCAccelerometer.h and CCAccelerometer.m files in your project.
  3. Import CCAccelerometer.h file in the Prefix.pch.
  4. Implement the <CCSharedAccelerometerDelegate> in the CCScene where you want to use the accelerometer.
  5. Create shared instance in init method by simply calling [CCAcceleroMeter sharedAccelerometer];
  6. Start accelerometer in -(void)onEnterTransitionDidFinish by calling [CCAcceleroMeter sharedAccelerometer]startUpdateForScene:self];
  7. Define delegate method -(void)acceleroMeterDidAccelerate:(CMAccelerometerData*)accelerometerData in your scene.
  8. Stop accelerometer in -(void)onExitTransitionDidStart by calling [CCAcceleroMeter sharedAccelerometer]stopUpdateForScene:self];

You can find out the example project in GitHub.

Upvotes: 1

Ben-G
Ben-G

Reputation: 5026

We've written a tutorial on exactly this: https://www.makegameswith.us/gamernews/371/accelerometer-with-cocos2d-30-and-ios-7

You need to use the CoreMotion framework.

Upvotes: 2

Related Questions