2012-03-31 60 views
1

此代码用于加速度计 方法中。以下代码中发生了什么?

它使用一个名为playerVelocity的CGPoint变量。

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
{ 
    //controls how quickly the velocity decelerates 
    float deceleration = 0.4f; 

    //determines how sensitive the accelerometer reacts 
    float sensitivity = 6.0f; 

    //how fast the velocity can be at most 
    float maxVelocity = 100; 

    playerVelocity.x = playerVelocity.x *deceleration + acceleration.x *sensitivity; 


    if (playerVelocity.x < -maxVelocity) 
    { 
     playerVelocity.x = -maxVelocity; 
    } 
    else if (playerVelocity.x > maxVelocity) 
    { 
     playerVelocity.x = maxVelocity; 
    } 
} 

现在我知道playerVelocity变量是一个CGPoint,所以我把它想象成一个X,Y图表。 我假设无论playerVelocity变量在哪里休息(比如说150,0),它首先将任何坐标乘以0.4,无论何时收到加速度计输入(这是由iPhone倾斜),然后加上accelerometer.x乘以6.0到playerVelocity变量。它是否正确?

后来在另一种方法,这是通过

CGPoint pos = playerObject.position; 
pos.x+= playerVelocity.x; 
playerObject.position = pos; 

添加到我的其他对象的位置我感到困惑的是究竟是什么幕后发生的事情在这里。我的假设是否正确?

当playerVelocity在150,0并且乘以0.4时,playerVelocity变量的X坐标是否逐渐减小,即150,0,145,0,130,0等。

如果我知道了,我会知道我的playerObject是如何移动的。

回答

1

看起来你有一个恒定的减速度(.4),它是在你正在行驶的任何方向上反向运动,通过加速度计乘以一个常数从加速度中减去。然后将此值添加到当前速度。因此,您基本上将每次计算中加速度计的加速度 - 恒定减速度与当前速度的差值相加。

+0

我明白了。 所以,这个动作基本上发生在我的另一种方法(这是一种更新方法),它将速度添加到位置。我明白,谢谢。 – 2012-03-31 00:33:59