开发者

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

+ (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 = %@", NSStri开发者_如何学GongFromCGPoint(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".

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.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜