根据加速度值以横向模式移动CCSprite(cocos2d)对象

时间:2011-07-15 14:48:40

标签: iphone cocos2d-iphone uiaccelerometer ccsprite

我正准备一个游戏,我想根据加速度值移动一个对象,游戏处于横向模式。

对于游戏,我使用cocos2d框架,我根据加速度值更改精灵位置,这是我的加速度计代码

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

其中player是CCSprite对象,Player按设备方向旋转,但不会根据设备方向更改位置。我究竟做错了什么?是否在横向模式下,x轴表现为y,y轴表现为x?

1 个答案:

答案 0 :(得分:0)

加速度x,y,z值与iPhone的描绘模式对齐。在其他模式中,您必须根据以下代码重新映射轴:

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

Kobold2D acceleration values are already mapped to the current device orientation中,您无需考虑这一点。