2011-05-05 38 views
1

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

回答

0

如果你想使它看起来更逼真,并充分利用现有的东西,看一些现有的物理引擎和2D框架,Box2D的和Cocos2d的,但也有许多其他问题。

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;