4

我试图找到最接近“球”的“玩家”,这些对象中的每一个都是 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

2 回答 2

4

像这样使用 @"%@" 的距离:

for(NSNumber *distance in distances ) {

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

}

[NSNumber numberWithInt:距离]

在你的第一部分距离是一个 CGFloat。

在第二部分距离是一个 NSNumber。

numberWithInt 不能将 NSNumber 作为其参数。

希望这可以帮助!

于 2011-07-06T10:16:06.407 回答
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;
    }
}
于 2014-06-11T07:09:56.423 回答