Loading...
Logo
Processing Forum
Depending on the "Learning Processing"-book, its better to have a function that tests the intersection of object INSIDE the class for that object.
Instead it seems more logic to me to have the function OUTSIDE any class, so you can call it for every object you like (not only to check if Ball Objects intersect, but also if other objects intersect).

Isn't this true?

Since we have programmed the balls in an object-oriented fashion, it is not terribly logical to suddenly have an intersect( ) function that lives outside of the ball class. A ball object should know how to test if it is intersecting another ball object.

Replies(2)

Well, we can defend each approach...

In the classical (in Processing) approach, each ball is an autonomous entity, already managing itself its moves. It seems logical to let it also check if it hits an obstacle, be it another ball, a wall, or something else. It is very natural to check for other balls, but perhaps a bit less for other obstacles, because it would need to know the nature of the other obstacles, and to change the code of the ball each time we add a new one.
Unless we find a common interface for all kinds of obstacles and use generic methods (the preferred name for functions in classes) to do this check, but it might be not obvious.
But well, for simple sketches like the bouncing balls, it is OK.

Another approach is to have a ball manager... Some kind of ball collection (holding an array or an array list, depending on the dynamic of the number of balls) which manages their moves (or can check their position and influence their direction, at least) and can manage collisions between balls.
Again, if the various objects share a common interface (or abstract class, but interface is better), it can also manage a collection of heterogeneous objects/shapes, and check for the collisions, among other things.
One advantage of this approach (kind of bird's eye) is that it allows optimizations, like using the quadtree algorithm to optimize the checks.

Somehow, when you talk about putting the intersection function out of the class, you delegate to the sketch (which is a class of its own) the responsibility of the object manager.
But it has other responsibilities, so in complex sketches, it is better to make a specialized class, isolating the functionality from others.
Thank you! Very complete and understandable explanation.