0

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

对于游戏,我使用 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 );
}

CCSprite 对象在哪里player,播放器根据设备方向旋转,但不会根据设备方向改变位置。我究竟做错了什么?是不是在横向模式下,x 轴表现为 y 而 y 轴表现为 x?

4

1 回答 1

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 中,加速度值已经映射到当前设备方向,因此您不必考虑这一点。

于 2011-10-23T21:22:10.283 回答