2

所以这是我正在开发的第一个练习游戏,也是第一次使用加速度计,所以如果答案很明显,请提前道歉。还想用代码和解释来回答。

所以在比赛的一部分,我有一个球在没有屏幕的情况下滚动。球根据倾斜移动。此应用程序的设备方向仅为横向。当我在保持手机横向的同时上下倾斜手机时,球会相应地移动。(将顶端向下倾斜,球会向上滚动,将底端向下倾斜,球会向下滚动)。所以这两个倾斜很好。现在,当我将屏幕左侧向下倾斜时,球向右滚动,反之亦然。我想要的是屏幕向左倾斜,球向左移动,屏幕向右倾斜,球向右移动。这是如何用我下面的代码解决的。我知道它可能就像更改两条线一样简单。

//delegate method
-(void)outputAccelertionData:(CMAcceleration)acceleration
{
    currentMaxAccelX = 0;
    currentMaxAccelY = 0;


    if(fabs(acceleration.x) > fabs(currentMaxAccelX))
    {
        // this needs to be currentMaxAccelY not currentMaxAccelX for those of you thinking this is the solution
        currentMaxAccelY = acceleration.x; 
    }
    if(fabs(acceleration.y) > fabs(currentMaxAccelY))
    {
        // this needs to be currentMaxAccelX not currentMaxAccelY for those of you thinking this is the solution
        currentMaxAccelX = acceleration.y;
    }
}

-(void)update:(CFTimeInterval)currentTime {

    /* Called before each frame is rendered */


    float maxY = 480;
    float minY = 0;


    float maxX = 320;
    float minX = 0;

    float newY = 0;
    float newX = 0;

    //Im pretty sure the problem is in this if statement as this is what deals with the left and right tilt
    if(currentMaxAccelX > 0.05){
        newX = currentMaxAccelX * 10;
    }
    else if(currentMaxAccelX < -0.05){
        newX = currentMaxAccelX*10;
    }
    else{
        newX = currentMaxAccelX*10;
    }

    newY = currentMaxAccelY *10;

    newX = MIN(MAX(newX+self.ball.position.x,minY),maxY);
    newY = MIN(MAX(newY+self.ball.position.y,minX),maxX);


    self.ball.position = CGPointMake(newX, newY);

}
4

1 回答 1

0

所以我解决了这个问题。问题出在我的数学上。而不是乘以 10,我应该乘以负 10 以获得相反的效果。

if(currentMaxAccelX > 0.05){
        newX = currentMaxAccelX * -10;
    }
    else if(currentMaxAccelX < -0.05){
        newX = currentMaxAccelX*-10;
    }
    else{
        newX = currentMaxAccelX*-10;
    }
于 2014-02-12T15:48:22.420 回答