I am using UIAccelerometer
in my game and it is working fine in portrait mode but not working properly in landscape mode.
Can some one fix the issue in my code
I am putting my code as below:
#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
The accelerometer axes do not change with change in orientation. You will have to handle the different orientation cases in your - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
method by detecting the current device orientation.