2010-08-13 107 views
1

我正在嘗試使隨機位置產生的物理物體以隨機速度撞擊目標。我收集並稍微修改了使用花栗鼠在Box2D的運行從網上這段代碼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; 
} 

問題是我不知道如何將其應用到我的節目,我有-20 y的重力但是把20換爲g,而把v換成10,對於v來說,除了「沒有解決方案」之外我什麼也得不到。

我在做什麼錯?

回答

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

你能解釋一下你將如何利用這一點,好嗎? – 2013-07-12 10:16:09