2011-07-06 83 views
4

我正在嘗試找到最接近「球」的「球員」,並且每個對象都是CCSprite對象。這是我的第一個應用程序,所以如果有更好的方式來做到這一點,隨意建議吧:)查找離我最近的CCSprite

這裏是我到目前爲止的代碼:

for(CCSprite *currentPlayer in players) { 

     // distance formula 
     CGFloat dx = ball.position.x - currentPlayer.position.x; 
     CGFloat dy = ball.position.y - currentPlayer.position.y; 
     CGFloat distance = sqrt(dx*dx + dy*dy); 

     // add the distance to the distances array 
     [distances addObject:[NSNumber numberWithFloat:distance]]; 

     NSLog(@"This happen be 5 times before the breakpoint"); 
     NSLog(@"%@", [NSNumber numberWithInt:distance]); 

} 

所以這似乎運作良好;它會記錄玩家距離球的每個距離。但後來當我依次通過我的「距離」陣列,像這樣:

for(NSNumber *distance in distances) { 

     NSLog(@"Distance loop"); 
     NSLog(@"%@", [NSNumber numberWithInt:distance]); 

} 

,這是每一次記錄一個龐大的數字,像220255312.我宣佈這樣我的距離排列:

// setting the distance array 
NSMutableArray *distances = [[NSMutableArray alloc] init]; 

我究竟做錯了什麼?

謝謝你的時間!

回答

4

爲@ 「%@」 像這樣使用距離:

for(NSNumber *distance in distances) { 

    NSLog(@"Distance loop"); 
    NSLog(@"%@", distance); 

} 

[NSNumber的numberWithInt:距離]

在您的第一部分距離是CGFloat的。

在第二部分距離是一個NSNumber。

numberWithInt不能接受一個NSNumber作爲它的參數。

希望這會有所幫助!

+0

它確實有幫助!看起來我一直都有正確的價值觀,乾杯Mikey! –

0
CCSprite *nearestPlayer; 
for(CCSprite *currentPlayer in players) { 
    if(nearestPlayer == nil){ 
     nearestPlayer = currentPlayer; 
    } 
    if(ccpDistance(ball.position, currentPlayer.position) < ccpDistance(ball.position, nearestPlayer.position)){ 
     nearestPlayer = currentPlayer; 
    } 
}