Using iPhone's accelerometer to move a sprite along the x-axis

I am working on an iPhone game using cocos2d. I am trying to use an accelerometer to move a sprite in portrait mode to move left and right. For some reason the code I use by default moves to the right UNLESS the phone is tilted at a 45 degree angle i.e. The return values ​​are positive (meaning it must move to the right) until it is tilted at a 45 degree angle, either left or right. The dead center comes back around 600 and then tilts the phone down further to the left or right until it reaches a 45-degree angle (where it reaches 0 and starts negative). Below is the code I am using. Any help would be GREAT appraisal.

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

        #define kFilteringFactor 0.75
            static UIAccelerationValue rollingX = 0, rollingY = 0, rollingZ = 0;

            rollingX = (acceleration.x * kFilteringFactor) +
            (rollingX * (1.0 - kFilteringFactor));
            rollingY = (acceleration.y * kFilteringFactor) +
            (rollingY * (1.0 - kFilteringFactor));
            rollingZ = (acceleration.z * kFilteringFactor) +
            (rollingZ * (1.0 - kFilteringFactor));

            float accelX = rollingX;
            float accelY = rollingY;
            float accelZ = rollingZ;

            CGSize winSize = [CCDirector sharedDirector].winSize;

        #define kRestAccelX 0.6
        #define kShipMaxPointsPerSec (winSize.height*0.5)
        #define kMaxDiffX 0.2

            float accelDiffX = kRestAccelX - ABS(accelX);
            float accelFractionX = accelDiffX / kMaxDiffX;
            float pointsPerSecX = kShipMaxPointsPerSec * accelFractionX;

            _shipPointsPerSecX = pointsPerSecX;
            NSLog(@"_shipPointsPerSecX: %f", _shipPointsPerSecX);
}

- (void)updateShipPos:(ccTime)dt {

    CGSize winSize = [CCDirector sharedDirector].winSize;

    float maxX = winSize.width - _ship.contentSize.width/2;
    float minX = _ship.contentSize.width/2;

    float newX = _ship.position.x + (_shipPointsPerSecX * dt);
    newX = MIN(MAX(newX, minX), maxX);
    _ship.position = ccp(newX, _ship.position.y);
   // NSLog(@"newx: %f", newX);

}

      

+3


source to share


1 answer


Basically what your accelerometer should do is update the acceleration (with the same filtering factor as you).

But next to it you have to maintain speed and position and adapt both in your planned (float dt) function and in the following:



Speed ​​+ = acceleration * dt Position + = speed * dt

Do it for x and y

+1


source







All Articles