Box2d计算轨迹

时间:2010-08-13 20:44:23

标签: iphone objective-c box2d

我试图让随机位置生成的物理体以随机速度击中目标。我收集并稍微修改了使用chipmunk在Box2d中运行的网页上的代码

+ (CGPoint) calculateShotForTarget:(CGPoint)target from:(CGPoint) launchPos with:(float) velocity
{
    float xp = target.x - launchPos.x;
    float y = target.y - launchPos.y;
    float g = 20;
    float v = velocity;
    float angle1, angle2;

    float tmp = pow(v, 4) - g * (g * pow(xp, 2) + 2 * y * pow(v, 2));

    if(tmp < 0){
        NSLog(@"No Firing Solution");
    }else{
        angle1 = atan2(pow(v, 2) + sqrt(tmp), g * xp);
        angle2 = atan2(pow(v, 2) - sqrt(tmp), g * xp);
    }

    CGPoint direction = CGPointMake(cosf(angle1),sinf(angle1));
    CGPoint force = CGPointMake(direction.x * v, direction.y * v);

    NSLog(@"force = %@", NSStringFromCGPoint(force));
    NSLog(@"direction = %@", NSStringFromCGPoint(direction));

    return force;
}

问题是我不知道如何将这个应用到我的程序中,我的重力为-20,但是20为g而较低的速度,如10为v,除了“No Firing Solution”之外什么都没有

我做错了什么?

1 个答案:

答案 0 :(得分:1)

较低的速度10永远不会起作用,射弹没有足够的力量来移动距离。

计算中的错误是除了以像素为单位的距离计算外,一切都以米为单位!

将代码更改为此修复了我获得的疯狂速度:

+ (CGPoint) calculateShotForTarget:(CGPoint)target from:(CGPoint) launchPos with:(float) velocity
{
    float xp = (target.x - launchPos.x) / PTM_RATIO;
    float y = (target.y - launchPos.y) / PTM_RATIO;
    float g = 20;
    float v = velocity;
    float angle1, angle2;

    float tmp = pow(v, 4) - g * (g * pow(xp, 2) + 2 * y * pow(v, 2));

    if(tmp < 0){
        NSLog(@"No Firing Solution");
    }else{
        angle1 = atan2(pow(v, 2) + sqrt(tmp), g * xp);
        angle2 = atan2(pow(v, 2) - sqrt(tmp), g * xp);
    }

    CGPoint direction = CGPointMake(cosf(angle1),sinf(angle1));
    CGPoint force = CGPointMake(direction.x * v, direction.y * v);

    NSLog(@"force = %@", NSStringFromCGPoint(force));
    NSLog(@"direction = %@", NSStringFromCGPoint(direction));

    return force;
}