UIAccelerometer问题与横向模式

时间:2014-03-11 12:11:35

标签: ios iphone objective-c cocos2d-iphone uiaccelerometer

我在游戏中使用UIAccelerometer,它在纵向模式下工作正常但在横向模式下无法正常工作。

有人可以在我的代码中解决问题

我的代码如下:

#import "GameLayer.h"


@implementation GameLayer


+(id)scene
{
    CCScene *scene = [CCScene node];
    CCLayer *layer = [GameLayer node];
    [scene addChild:layer];

    return scene;
}

- (id)init
{
    if ((self = [super init]))
    {
        self.isAccelerometerEnabled = YES;

        player = [CCSprite spriteWithFile:@"spaceship.png"];
        [self addChild:player];

        CGSize screenSize = [CCDirector sharedDirector].winSize;
        player.position = CGPointMake(screenSize.width / 2, screenSize.height / 2);

        [self scheduleUpdate];
    }

    return self; 
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    float deceleration = 1.0f;
    float maxVelocity = 50;

    playerVelocity.x = playerVelocity.x * deceleration + acceleration.x;
    playerVelocity.y = playerVelocity.y * deceleration + acceleration.y;

    if (playerVelocity.x > maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x < -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }


    if (playerVelocity.y > maxVelocity)
    {
        playerVelocity.y = maxVelocity;
    }
    else if (playerVelocity.y < -maxVelocity)
    { 
        playerVelocity.y = -maxVelocity; 
    } 
}

- (void)update:(ccTime)delta
{
    CGPoint pos = player.position; pos.x += playerVelocity.x;
    pos.y += playerVelocity.y;

    CGSize screenSize = [CCDirector sharedDirector].winSize;

    float imageWidthHalved = player.texture.contentSize.width * 0.5f;
    float imageHeightHalved = player.texture.contentSize.height * 0.5f;

    float leftBorderLimit = imageWidthHalved;
    float rightBorderLimit = screenSize.width - imageWidthHalved;
    float topBorderLimit = imageHeightHalved;
    float bottomBorderLimit = screenSize.height - imageHeightHalved;

    if (pos.x < leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        playerVelocity.x = 0;
    }
    else if (pos.x > rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        playerVelocity.x = 0;
    }

    if (pos.y < topBorderLimit)
    {
        pos.y = topBorderLimit;
        playerVelocity.y = 0; }
    else if (pos.y > bottomBorderLimit)
    {
        pos.y = bottomBorderLimit;
        playerVelocity.y = 0; 
    }

    player.position = pos; 
}

@end

1 个答案:

答案 0 :(得分:0)

加速度计轴不随方向变化而变化。您必须通过检测当前的设备方向来处理- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration方法中的不同方向情况。