2

我正在使用 Box2D 在 Objective C 中创建汽车游戏。我想根据 CCSprite(转向)旋转来旋转车轮。

因此,为此,我能够根据触摸成功设置 CCSprite 转向的角度。但是当我试图获得转向旋转的价值时,尽管转向完美旋转,但它并没有得到完美的结果。但弧度角值有时并不完美。所以我无法按照转向旋转来旋转车轮

我的代码是设置转向角度如下

On Touch Begin,设置起始角度

-(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
}

这是原木,当移动转向时,逆时针方向

-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
4

1 回答 1

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;
于 2013-04-23T09:37:00.297 回答