2012-04-29 62 views
0

下午好!Cocos2D和iPhone的加速度計

今天我開始開發一款遊戲,並且遇到了麻煩。所以,首先我想說,我沒有經驗開發遊戲......

所以,我在圖層中有一個CCSprite,我想在邊距(頂部,底部, 左和右)。

最小的X應該是-0.8(在使用加速度計的X軸上)並且最大值爲8.最小值Y應該是-1(在Y軸上)或者0在Z軸上並且最大值0 Y軸)或-1(Z軸)。

好吧,知道這一點,我試圖使用最小和最大空間和加速度計值之間的範圍,但我沒有得到垂直工作(iPhone上的Y軸)。然後,我在網上得到了一個完成的代碼,但是當我想要將對象移回(僅僅是對象)時,這不起作用。

有人知道如何解決這個問題嗎?

我的實際代碼:

- (void)updatePosition:(ccTime)dt { 
    CGSize winSize = [[CCDirector sharedDirector] winSize]; 

    float maxY = winSize.height - car.contentSize.height/2 - 20; 
    float minY = car.contentSize.height/2 + 20; 
    float newY = car.position.y + (carPointsPerSecY * dt); 
    newY = MIN(MAX(newY, minY), maxY); 

    float maxX = winSize.width - car.contentSize.width/2 - 40; 
    float minX = car.contentSize.width/2 + 40; 
    float newX = car.position.x + (carPointsPerSecX * dt); 
    newX = MIN(MAX(newX, minX), maxX); 

    car.position = ccp(newX, newY); 
}  

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { 
    float speedY = acceleration.y * 500; 
    if(carPointsPerSecY < speedY) { 
     carPointsPerSecY = MIN(carPointsPerSecY + 10, speedY); 
    } else { 
     carPointsPerSecY = MAX(carPointsPerSecY - 2, speedY); 
    } 

    float speedX = acceleration.x * 200; 
    if(carPointsPerSecX < speedX) { 
     carPointsPerSecX = MIN(carPointsPerSecX + 10, speedX); 
    } else { 
     carPointsPerSecX = MAX(carPointsPerSecX - 10, speedX); 
    } 

    NSLog(@"Acceleration: X (%f) - Y (%f) - Z (%f)", acceleration.x, acceleration.y, acceleration.z); 
} 
+0

你允許它使用加速度計?另外,NSLog是否顯示加速度計正在改變? –

+0

是的,它的工作。問題不在於此:/ –

+0

carPointPerSecX/Y是什麼類型? –

回答

0

我不知道我完全理解你想要什麼,但我希望這有助於你和你的最終目標:

-(void)updatePosition:(ccTime)dt { 
    CGSize size = [[CCDirector sharedDirector] winSize]; 

    int margin = 20; 
    float speed = 15; 

    float maxX = size.width - car.contentSize.width/2 - margin; 
    float minX = car.contentSize.width/2 + margin; 
    float maxY = size.height - car.contentSize.height/2 - margin; 
    float minY = car.contentSize.height/2 + margin; 

    float newX = MIN(MAX(car.position.x + xAccel * speed, minX), maxX); 
    float newY = MIN(MAX(car.position.y + yAccel * speed, minY), maxY); 

    car.position = ccp(newX, newY); 
} 

//define in header: float xAccel, yAccel; 
- (void)accelerometer: (UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration { 
    yAccel = acceleration.x; 
    xAccel = -acceleration.y; 
}