我正在使用Box2D在Objective C中创建一个汽车游戏。我想根据CCSprite(转向)旋转来旋转车轮。
所以为此,我成功地根据触摸设置了CCSprite Steering的角度。但是当我试图获得Steer旋转的价值时,它并没有得到完美的结果,尽管Steer旋转完美。但Radian 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);
}
触摸移动,移动转向和设置轿厢角度
-(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
}
这是Log,当移动Steer时,逆时针方向
-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
答案 0 :(得分:1)
终于得到了答案。感谢Box2D论坛(http://box2d.org/forum/viewtopic.php?f=5&t=4726)
对于Objective C,我们必须将角度标准化,如下面的函数。
-(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);
}
在条件检查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;