用加速计倾斜iphone使球滚动



我正在制作一个iphone应用程序,其中一个球将根据用户倾斜设备的方式在屏幕上滚动。如果这个装置平放在桌子上,理论上球就不会动。如果设备完全向上倾斜,我希望球以最大速度直滚下来。速度取决于设备倾斜距离平面位置的距离。此外,它也适用于用户向右、向左或向上倾斜或这四种方式的组合。我现在正在使用加速计,球在运动,它工作得很好,我只是对物理不太熟悉。如果有人对如何使这个工作顺利进行有任何建议,请告诉我。

谢谢!

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
float xx = -[acceleration x];
float yy = [acceleration y];
float z = -[acceleration z];
z = 1 - z;

NSString * zaxis = [NSString stringWithFormat:@"%f", z];
lblz.text = zaxis;
lbly.text = [NSString stringWithFormat:@"%f", yy];
lblx.text = [NSString stringWithFormat:@"%f", xx];

CGFloat newx;
CGFloat newy;
if (yy > 0)
{
    newy = ball.center.y - ((1 - yy) * z);
}
else
{
    newy = ball.center.y + ((1 - yy) * z);
}
if (xx > 0)
{
    newx = ball.center.x - ((1 - xx) * z);
}
else
{
    newx = ball.center.x + ((1 - xx) * z);
}
CGPoint newPoint = CGPointMake(newx, newy);
ball.center = newPoint;

如果你想让它看起来更真实,并利用现有的东西,看看一些现有的物理引擎和2d框架,Box2d和Cocos2d,但还有很多其他的。

我认为你在这里搞混的关键是加速度和速度之间的区别。你希望"倾斜量"作为加速度。每一帧,球的速度应该随着加速度而变化,然后球的位置应该随着球的速度而变化。

在X中应该是这样的

float accelX = acceleration.x;
mVel.x += accelX;  \mVel is a member variable you have to store
ball.center.x += mVel.x;

—更复杂的版本

现在我想得越多,它可能不是你想要的"倾斜量"是加速度。你可能希望倾斜度是目标速度但是你仍然需要使用加速度来到达那里。

mTargetVel.x = acceleration.x;
//Now apply an acceleration to the velocity to move towards the Target Velocity
if(mVel.x < mTargetVel.x) {
   mVel.x += ACCEL_X;  //ACCEL_X is just a constant value that works well for you
} 
else if(mVel.x > mTargetVel.x) {
   mVel.x -= ACCEL_X;  
} 
//Now update the position based on the new velocity
ball.center.x += mVel.x;

最新更新