In an arbitrary physics engine for a game, there exists a "Shape" superclass and its derived subclasses such as "AABB" or "Triangle". Collision detection methods between each pair is unique, for example the AABB-Sphere test will obviously be different from the Triangle-AABB test. If I have two collections of shapes as such and I wish to check some collisions between them:
// somewhere in the program
Shape* shape_a;
Shape* shape_b;
....
if (shape_a->intersects(shape_b)) {
// do something
}
How can specific collision checks (e.g. AABB-ABBB, or AABB-Sphere) be performed? For example, if shape_a points to a derived Triangle object, and shape_b performs to a derived AABB object, how can the intersects function correctly compare a Triangle and AABB object? My current implementation is as follows but it does not compile as an include loop is created (likely due to bad OOP practice).
Shape.h
#include "AABB.h"
#include "triangle.h"
class Shape {
public:
virtual bool intersects(Shape* shape) = 0;
virtual bool intersects(AABB aabb) = 0;
virtual bool intersects(Triangle tri) = 0;
}
AABB.h
#include "shape.h"
class AABB : public Shape {
// overriden functions
bool intersects(Shape* shape);
bool intersects(AABB aabb); // aabb-aabb
bool intersects(Triangle tri); // aabb-tri
}
triangle.h
#include "shape.h"
class Triangle : public Shape {
// overriden functions
bool intersects(Shape* shape);
bool intersects(AABB aabb); // tri-aabb
bool intersects(Triangle tri); // tri-tri
}
The implementation for an intersects(Shape* shape) function looks like:
// in AABB.cpp
bool intersects(Shape* shape) {
return shape.intersects(*this); // where *this is an AABB object
}
And of course, I want to avoid code duplication: the tri-aabb test is the same as the aabb-tri test. Perhaps I am writing code that is fundamentally flawed and is bad OOP practice. In any case, I'd appreciate any help with this problem!