简体   繁体   English

Box2d计算轨迹

[英]Box2d Calculating Trajectory

I'm trying to make physics bodies generated at a random position with a random velocity hit a target. 我试图使以随机速度在随机位置生成的物理物体撞击目标。 I gleaned and slightly modified this code from the web that was using chipmunk to run in Box2d 我从使用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;
}

The problem is I don't know how to apply this to my program, I have a gravity of -20 for y but putting 20 for g and a lower velocity like 10 for v gets me nothing but "No Firing Solution". 问题是我不知道如何将其应用到我的程序中,y的重力为-20,g的重力为20,v的速度为10,例如10,则没有“除火解决方案”。

What am I doing wrong? 我究竟做错了什么?

A lower velocity of 10 is never going to work the projectile doesn't have enough power to travel the distance. 较低的10速度永远不会起作用,而射弹则没有足够的动力来穿越距离。

The error in the calculation is that everything is in meters except for the distance calculations which are in pixels! 计算中的错误是,除以像素为单位的距离计算外,其他所有内容均以米为单位!

Changing the code to this fixed the crazy velocities i was getting: 将代码更改为此可解决我得到的疯狂速度:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM