Brandon Lassiter
Brandon Lassiter

Reputation: 306

Using the iPhone accelerometer to move a sprite along the x axis

I am working on an iPhone game using cocos2d. I am trying to use the accelerometer for movement of a sprite in portrait mode to move left and right. For some reason with the code I am using it defaults to moving right UNLESS the phone is tilted at a 45 degree angle, i.e. the returned values are all positive(indicating it should move to the right) until it is tilted at a 45 degree angle, either left or right. Dead center is returning around 600 and then decreasing the further you tilt the phone left or right until it gets to a 45 degree angle (where it hits 0 and starts to go negative). Below is the code I am using. Any help would be GREATLY appreciate.

- (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);

}

Upvotes: 3

Views: 1394

Answers (1)

Stephane Delcroix
Stephane Delcroix

Reputation: 16232

Basically, what your accelerometer should do is updating the acceleration (with a filtering factor like you do).

But next to it you should maintain velocity and position, and adapt both in your scheduled step(float dt) function like this:

Velocity += acceleration*dt Position += velocity * dt

Do that for x and y

Upvotes: 1

Related Questions