Search code examples
objective-ccocos2d-iphoneccsprite

Find the closest CCSprite


I am trying to find the closest "player" to a "ball" and each of these objects are CCSprite Objects. This is my first app, so if there's a better way to do this, feel free to suggest it :)

Here's my code so far:

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]);

}

So this seems to work well; it logs each distance of the player from the ball. But then when I loop through my "distances" array, like this:

for(NSNumber *distance in distances ) {

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

}

And this is logging a huge number each time, like 220255312. I declare my distances array like this:

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

What am I doing wrong?

Thanks for your time!


Solution

  • Use distance for the @"%@" like this:

    for(NSNumber *distance in distances ) {
    
        NSLog(@"Distance loop");
        NSLog(@"%@", distance);
    
    }
    

    [NSNumber numberWithInt:distance]

    In your first part distance is a CGFloat.

    In the second part distance is a NSNumber.

    numberWithInt can't take a NSNumber as its argument.

    Hope this helps!