ios - 加速度计倾斜问题

标签 ios ios7 accelerometer uiaccelerometer

因此,这是我正在开发的第一款练习游戏,并且是首次使用加速度计,因此如果答案很明显,请提前道歉。还要提供代码和解释。

因此,在游戏的一部分中,我有一个球没有在屏幕上滚动。球根据倾斜度移动。此应用程序的设备方向仅适用于横向。当我握住手机横向并向上和向下倾斜手机时,球会相应移动。 (将顶端向下倾斜,使球向上滚动,将底端向下倾斜,使球向下滚动)。因此,这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);

}

最佳答案

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

if(currentMaxAccelX > 0.05){
        newX = currentMaxAccelX * -10;
    }
    else if(currentMaxAccelX < -0.05){
        newX = currentMaxAccelX*-10;
    }
    else{
        newX = currentMaxAccelX*-10;
    }

关于ios - 加速度计倾斜问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21714388/

相关文章:

ios - UICollectionView 找不到成员

c# - 如何在 WP7 中的枢轴页面上应用加速度计来导航页面?

ios - MKAnnotation 需要在长按可拖动之前单击

ios - UICollectionViewCell : Reused Cell with UIImageView item not refreshed after image and size changes

ios - Swift 将变量设置为另一个 ViewController

orientation - R如何为所有传感器注册SensorEventListener

iphone - 使用带有 CMMotionManager 的串行队列

ios - 扩展中的声明还不能覆盖

ios - 更改 UIActionSheet 样式在 iOS 7 中没有区别吗?

ios - 文本换行后 UITextView 大小不会改变大小,直到键入第二个字符