1

我正在制作一个 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;
4

2 回答 2

0

我认为你在这里搞砸的关键是加速度和速度之间的差异。您希望“倾斜量”作为加速度起作用。每一帧球的速度都应该随着加速度的变化而变化,然后球的位置应该随着球的速度而变化。

所以就在 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;
于 2011-05-06T16:47:59.577 回答
0

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

于 2011-05-05T17:37:20.387 回答