1

I'm trying to make the box2d accelerometer work, I have a car sprite and want it to move left and right, when the iPhone is tilted.

Here is the code for the sprite:

- (void)spawnCar {

car = [CCSprite spriteWithSpriteFrameName:@"car.jpg"];
car.position = ccp(160, 250);
car.tag = 2;

[self addBoxBodyForSprite:car];

[_spriteSheet addChild:car];

}

How can implement the accelerometer to work for left and right?

Dan D.
  • 73,243
  • 15
  • 104
  • 123
sahil
  • 141
  • 1
  • 9

1 Answers1

1

Just do this...

in your init add

self.isAccelerometerEnabled = YES;

and then add this method...

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    b2Vec2 gravity(-acceleration.y * 15, acceleration.x *15);
    world->SetGravity(gravity);

}
Jer In Chicago
  • 828
  • 5
  • 7
  • but how do i make the actual sprite move? – sahil Feb 21 '12 at 13:40
  • @sahil you will have to get the body position and then update the sprite to match that location. See the `tick` method available at http://www.raywenderlich.com/28602/intro-to-box2d-with-cocos2d-2-x-tutorial-bouncing-balls – McArthey Apr 14 '13 at 16:55