I am using below formula to move the ball circular, where accelX and accelY are the values from accelerometer, it is working fine.
But the problem in this code is mRadius (I fixed its value to 50), i need to change mRadius according to accelerometer values and also i need bouncing effect when it touches the track. Currently i am developing code by assuming only one ball is on the board.
float degrees = -atan2(accelX, accelY) * 180 / 3.14159;
int x = cCentrePoint.x + mRadius * cos(degreesToRadians(degrees));
int y = cCentrePoint.y + mRadius * sin(degreesToRadians(degrees));
Here is the snap of the game i want to develop:
Updated: I am sending the updated code...
mRadius = 5;
mRange = NSMakeRange(0,60);
-(void) updateBall: (UIAccelerationValue) accelX withY:(UIAccelerationValue)accelY
{
float degrees = -atan2(accelX, accelY) * 180 / 3.14159;
int x = cCentrePoint.x + mRadius * cos(degreesToRadians(degrees));
int y = cCentrePoint.y + mRadius * sin(degreesToRadians(degrees));
//self.targetRect is rect of ball Object
self.targetRect = CGRectMake(newX, newY, 8, 9);
self.currentRect = self.targetRect;
//http://books.google.co.in/books?id=WV9glgdrrrUC&pg=PA455#v=onepage&q=&f=false
static NSDate *lastDrawTime;
if(lastDrawTime!=nil)
{
NSTimeInterval secondsSinceLastDraw = -([lastDrawTime timeIntervalSinceNow]);
ballXVelocity = ballXVelocity + (accelX * secondsSinceLastDraw) * [self isTouchedTrack:mRadius andRange:mRange];
ballYVelocity = ballYVelocity + -(accelY * secondsSinceLastDraw) * [self isTouchedTrack:mRadius andRange:mRange];
distXTravelled = distXTravelled + secondsSinceLastDraw * ballXVelocity * 50;
distYTravelled = distYTravelled + secondsSinceLastDraw * ballYVelocity * 50;
CGRect temp = self.targetRect;
temp.origin.x += distXTravelled;
temp.origin.y += distYTravelled;
int radius = (temp.origin.x - cCentrePoint.x) / cos(degreesToRadians(degrees));
if( !NSLocationInRange(abs(radius),mRange))
{
//Colided with the tracks...Need a better logic here
ballXVelocity = -ballXVelocity;
}
else
{
// Need a better logic here
self.targetRect = temp;
}
//NSLog(@"angle = %f",degrees);
}
[lastDrawTime release];
lastDrawTime = [ [NSDate alloc] init];
}
In the above code i have initialized mRadius and mRange(indicate track) to some constant for testing, i am not getting the moving of the ball as i expected( bouncing effect when Collided with track ) with respect to accelerometer. Help me to recognize where i went wrong or send some code snippets or links which does the similar job.
I am searching for better logic than my code, if you found share with me.