문제

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 = %@", 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".

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top