I am creating a Car Game in Objective C with Box2D. I want to rotate the Car Wheels according to a CCSprite (Steering) Rotation.
So For this, i am successfully able to set the angle for CCSprite Steering according to touch. But when i am trying to get the Value of Steer rotation then Its not getting perfect result, although Steer is rotating perfectly. But Radian Angle value is not perfect some times. So i am not able to rotate wheels as per Steering rotation
My Code is to set the Steering Angle is as below
On Touch Begin, setting Starting angle
-(void)getAngleSteer:(UITouch *) touch
{
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
float adjacent = steering.position.x - location.x;
float opposite = steering.position.y - location.y;
self.startAngleForSteer = atan2f(adjacent, opposite);
}
On Touch Move, Moving Steering and Setting Car Angle
-(void)rotateSteer:(UITouch *) touch
{
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
float adjacent = steering.position.x - location.x;
float opposite = steering.position.y - location.y;
float angle = atan2f(adjacent, opposite);
angle = angle - self.startAngleForSteer;
steering.rotation = CC_RADIANS_TO_DEGREES(angle);
//Main issue is in below line
NSLog(@"%f %f", angle, CC_RADIANS_TO_DEGREES(angle));
if(angle > M_PI/3 || angle < -M_PI/3) return;
steering_angle = -angle;//This is for Box2D Car Angle
}
This is the Log, when moving Steer, anticlock wise
-0.127680 -7.315529
-0.212759 -12.190166
-0.329367 -18.871363
5.807306 332.734131 // Why is 5.80 cuming just after -0.32 it should be decrease.
5.721369 327.810303
5.665644 324.617462
Finally Got the answer for this. Thanks to Box2D forum (http://box2d.org/forum/viewtopic.php?f=5&t=4726)
For Objective C we have to normalize the angle like below function.
-(float) normalizeAngle:(float) angle
{
CGFloat result = (float)((int) angle % (int) (2*M_PI));
return (result) >= 0 ? (angle < M_PI) ? angle : angle - (2*M_PI) : (angle >= -M_PI) ? angle : angle + (2*M_PI);
}
And just call it before the condition check M_PI/3
steering.rotation = CC_RADIANS_TO_DEGREES(angle);
angle = [self normalizeAngle:angle];//This is where to call.
if(angle > M_PI/3 || angle < -M_PI/3) return;
steering_angle = -angle;