While working on a really only-for-fun project I encountered some problem.
There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens.
The thing I'd like to do is to make a way of detecting Collision between them. Here's what I'm standing on right now:
- For me Ball-Ball is easy, I just calculate their distance from their positions and compare it with the sum of their 'sizes'.
- Collision between Ball and edge of the world is simple too - I just check the distance from it, which, in Cartesian coordinates, is simple.
- More generic problems are - how to detect a collision between Line (starting and ending at some points) or other objects I could have there? Distance between a line and a point can be calculated easily too, but what I'd like is to have
Some kind of generic way to say if Obcject A
collides with Object B
. The code as it is now looks somewhat like:
class WorldCreature:
def detectCollision(self, otherObject):
# do something
if collision:
self.onCollision(otherObject)
otherObject.onCollision(self)
class Ball(WorldCreature):
# someing here
class Line(WorldCreature):
# someing here
Now, the collision detection mechanizm should depend on what objects can collide. So will the effect.
Should I just keep a list of all the objects in memory and loop through all them in every single step? Or, is there some better way to improve the performance of this task?