Collision Detection for 5 objects at once

1 reply [Last post]
Offline
Joined: 01/13/2011

Hey Everyone,
I'm working on Lesson 3 (Polymorphism) And I'm have problems with the 4th exercise. I cannot seem to figure how to get 5 tuxes to check if they are in range with each other and thus all die.
The only way I have so far is a ridiculous 5 nested loops (one for each Tux) to check, but this just epically slowed down the game to basically crashing.
Jake started showing me how he built an array to check this, but I can't seem to recreate what he had.
Any feedback is greatly appreciated,
Thanks,
-Sean

Offline
Joined: 12/13/2010
While a 5 level nested loop

While a 5 level nested loop would work, as you have observed, it is very inefficient.  Instead of thinking along the lines of loops, try to approach this challenge using a "count" approach.  Imagine that you have a Tux object named t already define, and you want to find out how many other Tux objects in the creatures ArrayList are close to it, you can use the following code:


int count = 0;
for (Creature c : creatures) {
    // Make sure that c is a different Tux that is close to t
    if (t != c && c instanceof Tux && distance(c,t)<2) {
        count++;
    }
}
// At this point, you'll have a count of how many Tuxes are close to t
System.out.println(count+" number of tuxes are close to t");

 

The above code simply counts the number of Tuxes close to t.  You'll need actually need to do something else inside the if statement to eliminate the tuxes.

This is just a hint.  If you need more help, let me know.