开发者

Making ball roll with iphone being tilted using Accelerometer

开发者 https://www.devze.com 2023-03-02 22:16 出处:网络
I am making an iphone app where a ball will roll around the screen based on how the user tilts the device.If the device is lies flat on the table theoretically the ball would not move.If the device is

I am making an iphone app where a ball will roll around the screen based on how the user tilts the device. If the device is lies flat on the table theoretically the ball would not move. If the device is tilted standing completely upward the I want the ball to roll straight down at maximum speed. The speed depends on how far from the flat position the device is tilted. Also, it also works for if the user tilts right or left or up or combinations of the four. I am using the accelerometer right now and the ball moves and it works okay, I am just not real familiar with physics. If someone has any suggestions on how to get this to work smoothly please let me know.

Thanks!

- (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.c开发者_开发问答enter.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;


If you want to make it look more realistic and leverage existing stuff, look at some of the existing physics engines and 2d frameworks, Box2d and Cocos2d, but there are many others.


I think the key thing you are messing here is the difference between acceleration and velocity. You want the 'amount of tilt' to work as an acceleration. Each frame the balls Velocity should change by the acceleration, then the balls position should change by the balls velocity.

So just in X it should be something like:

float accelX = acceleration.x;

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

ball.center.x += mVel.x;

---More Complex version

Now the more I think about it, it might not be the 'amount of tilt' you want to be the acceleration. You might want the amount of tilt to be the 'Target Velocity.' But you still want to use an acceleration to get there.

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号