0

I am preparing one game for which I want to move one object according to acceleration values, Game is in landscape mode.

For game, I am using cocos2d framework, and I am changing sprite position as per acceleration values, Here is my code of accelerometer

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration{
static float prevX=0, prevY=0, prevZ=0;
float accelX = acceleration.x * kFilterFactor + (1- kFilterFactor)*prevX;
float accelY = acceleration.y * kFilterFactor + (1- kFilterFactor)*prevY;
float accelZ = acceleration.z * kFilterFactor + (1- kFilterFactor)*prevZ;


prevX = accelX;
prevY = accelY;
prevZ = accelZ;

NSLog(@"x:%.2f,y:%.2f,z:%.2f",accelX, accelY, accelZ);

if ( ((player.position.x + (-accelY*kSpeed)) >0 && (player.position.x + (-accelY*kSpeed))<480)||
     ((player.position.y + (accelX*kSpeed)) >0 && (player.position.y + (accelX*kSpeed))<320)){

    player.position = ccp(player.position.x + (-accelY*kSpeed), player.position.y + (accelX*kSpeed));
}


CGPoint converted = ccp( (float)-acceleration.y, (float)acceleration.x);

// update the rotation based on the z-rotation
// the sprite will always be 'standing up'
player.rotation = (float) CC_RADIANS_TO_DEGREES( atan2f( converted.x, converted.y) + M_PI );
}

where player is CCSprite object, Player is rotated as per device orientation, but it does not change position as per device orientation. What am I doing wrong? Is it that in landscape mode, x axis behaves as y and y axis behaves as x?

jigneshbrahmkhatri
  • 3,627
  • 2
  • 21
  • 33

1 Answers1

0

The acceleration x, y, z values are aligned to the iPhone's portray mode. In other modes you will have to remap the axes according to this code:

-(void) setAccelerationWithX:(double)x y:(double)y z:(double)z
{
    rawZ = z;

    // transform X/Y to current device orientation
    switch ([CCDirector sharedDirector].deviceOrientation)
    {
        case kCCDeviceOrientationPortrait:
            rawX = x;
            rawY = y;
            break;
        case kCCDeviceOrientationPortraitUpsideDown:
            rawX = -x;
            rawY = -y;
            break;
        case kCCDeviceOrientationLandscapeLeft:
            rawX = -y;
            rawY = x;
            break;
        case kCCDeviceOrientationLandscapeRight:
            rawX = y;
            rawY = -x;
            break;
    }
}

In Kobold2D acceleration values are already mapped to the current device orientation, so that you don't have to consider this.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217