Riccardo Cecolin wrote:
>> If I have two balls and I want to detect whether they instersect with
>> each other as they move around the screen this is simple enough; the
>> ball class has an intersect() method which i can use to pass in a
>> reference to the other ball object. But what if there are are random
>> number of balls. How do I make it such that any Ball object would be
>> aware of the location of any other Ball object without having to resort
>> to nested for loops where I check the location of each Ball against
>> every other Ball?
>>     
First, look at the #each method and its siblings. These will encapsulate 
the loops.

For a reasonable number of balls, you could use an array to keep track 
of all the balls, then something like:

    intersects_with = []
    balls.each do | a_ball |
        if my_ball.intersect( a_ball )
          intersects_with << a_ball
       end
    end

There are other similar iterator methods that can help simplify that 
code. Incidently, it hasn't been executed.

When you have lots of balls or more complicated shapes, this problem 
becomes computationally "interesting". It is very likely to be discussed 
in books on graphics targeted for game programmers or others working 
with 3D graphics.

All the comparisons have to be done. With suitable data structures and 
algorithms, you may be able to save the results of the comparisons and 
not have to do some of  them again. But the algorithms and structures 
get complicated quickly.

Perhaps someone will point you to a ruby library that is intended for 
this sort of thing.
   
-- Bill