Kyle Goslan
Kyle Goslan

Reputation: 10920

Cocos2d Accelerometer Landscape

Im having trouble getting the accelerometer to work correctly in landscape mode with cocos2d. Everything works perfectly in portrait, but cant figure out how to flip it to correctly work in landscape. here is my code:

-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{

float deceleration = 0.0f;
float sensativity = 15.0f;
float maxVelocity = 100;

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

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 screeSize = [[CCDirector sharedDirector]winSize];

float imageHalf = [player texture].contentSize.width * 0.5f;

float leftLimit = imageHalf;
float rightLimit = screeSize.width - imageHalf -20;

float bottomLimit = imageHalf;
float topLimit = screeSize.height - imageHalf - 20;

if (pos.y < bottomLimit) {
    pos.y = bottomLimit;
}
else if (pos.y > topLimit){
    pos.y = topLimit;
}

if (pos.x < leftLimit) {
    pos.x = leftLimit;
}
else if (pos.x > rightLimit){
    pos.x = rightLimit;
}

player.position = pos;
}

Upvotes: 2

Views: 739

Answers (2)

Guru
Guru

Reputation: 22042

Look at answer in this question

Best way for accelerometer usage in cocos2d game.

Upvotes: 1

CodeSmile
CodeSmile

Reputation: 64477

In landscape orientation, the accelerometer x and y values are flipped. Furthermore, in interface orientation landscape right, x is negative. In landscape left, y is negative:

// landscape right:
position.x = -acceleration.y
position.y = acceleration.x

// landscape left:
position.x = acceleration.y
position.y = -acceleration.x

Upvotes: 3

Related Questions