Problem moving PhysicsBody with Accelerometer

I’m trying to move a Sprite with accelerometer just on X-axis, but the movement is not smooth and takes a long time to see the change of movement left/right. My world has a edgeBox with DEFAULT MATERIAL and sometimes i see my Sprite overlap the edge.

The body settings of Sprite:

auto body = PhysicsBody::createBox(size, PhysicsMaterial(0,0,0));
 body->setMass(0.1);

Accelerometer callback:

void HelloWorld::onAcceleration(cocos2d::Acceleration *acc, cocos2d::Event *event) { 
   #define kFilterFactor 5.0f
    this->acceleration = acc->x * kFilterFactor;
}

Update:

void HelloWorld::update(float dt){
    sprite->getPhysicsBody()->applyImpulse(Vec2(acceleration, 0));
}

What i’m doing wrong?

I realize that the problem is the accelerometer response, when i build the project sometimes it works perfectly but sometimes not. Sometimes the output of  CCLOG(“acc.x: %f”, acc->x)  shows a very slow response, maybe 10 seconds to change from 0.9998 to -0.9998. I really want to know why this is happening.

I had same problem and find solution.
Block structure in CCDevice - (void) setAccelerometerEnabled: (bool) isEnabled makes this delay.

Detail description

So, my solution is

- (void)accelerometer:(CMAccelerometerData *)accelerometerData
{
    _acceleration->x = _motionManager.accelerometerData.acceleration.x;
    _acceleration->y = _motionManager.accelerometerData.acceleration.y;
    _acceleration->z = _motionManager.accelerometerData.acceleration.z;
    _acceleration->timestamp = accelerometerData.timestamp;

It does not delay.

1 Like

wow! works pretty good! thank you so much :smile:

I also had the same problem/solution here: Accelerometer data lagging maybe we can introduce this to the official repo? I’m not sure if the queued data is needed for gaming purposes. Maybe someone from the cocos2d-x team can give a comment about this?

Strong agree!