代码之家  ›  专栏  ›  技术社区  ›  Neil Foley

Box2d计算轨迹

  •  1
  • Neil Foley  · 技术社区  · 15 年前

    我试图让物理物体以随机的速度,以随机的位置撞击目标。我从使用chipmunk在Box2d中运行的web上收集并稍微修改了这段代码

    + (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的y,但是把20的g和一个更低的速度,比如10的v,只能得到“无射击解”。

    我做错什么了?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Neil Foley    15 年前

    速度低于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;
    }