1

我试图让在随机位置生成的物理物体以随机速度击中目标。我从使用花栗鼠在 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;
}

问题是我不知道如何将它应用到我的程序中,y 的重力为 -20,但 g 的重力为 20,v 的速度为 10 的较低速度只能让我“无点火解决方案”。

我究竟做错了什么?

4

1 回答 1

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;
}
于 2010-08-14T07:32:48.340 回答