I am making a game that requires hitboxes.
There will be rectangular and circular hitboxes.
I want a function that returns a bool that indicates whether any two hitboxes are overlapping.
Both shapes must be able to be stored in the same container at once.
Should I just have one class contain all the variables for both shapes and use a "shape" variable to indicate which shape related variables to ignore completely? (What would the constructor look like?)
Or should I have 2 separate, similarly structured, classes?
I want a function that returns a bool that indicates whether any two hitboxes are overlapping.
I have yet to find a really good way to do this polymorphically. If you know you are going to only have 2 different kinds of hitboxes, you can probably get away with a few if/else checks. But if you want it to be expandable that approach kind of sucks.
class HitBoxRect;
class HitBoxCirc;
class HitBox
{
public:
virtual ~HitBox() { }
virtualbool Overlap(HitBox&) = 0;
inlinestaticbool Overlap(HitBox& a,HitBox& b) { return a.Overlap(b); } // alternate entry
virtualbool Overlap(HitBoxRect&) = 0;
virtualbool Overlap(HitBoxCirc&) = 0;
// add more functions here as you introduce more types
protected:
staticbool Overlap_RectRect(HitBoxRect& a, HitBoxRect& b); // write your bodies for these
staticbool Overlap_RectCirc(HitBoxRect& a, HitBoxCirc& b);
staticbool Overlap_CircCirc(HitBoxCirc& a, HitBoxCirc& b);
// and also here
};
class HitBoxRect : public HitBox
{
public:
// put rect dims and stuff here
virtualbool Overlap(HitBox& b) { return b.Overlap(*this); }
virtualbool Overlap(HitBoxRect& b) { Overlap_RectRect(*this,b); }
virtualbool Overlap(HitBoxCirc& b) { Overlap_RectCirc(*this,b); }
};
class HitBoxCirc : public HitBox
{
public:
// put circle radius and stuff here
virtualbool Overlap(HitBox& b) { return b.Overlap(*this); }
virtualbool Overlap(HitBoxRect& b) { Overlap_RectCirc(b,*this); }
virtualbool Overlap(HitBoxCirc& b) { Overlap_CircCirc(*this,b); }
};
// example usage:
HitBoxRect a = whatever;
HitBoxCirc b = whatever;
if(a.Overlap(b))
{
}
// alternatively
if(HitBox::Overlap(a,b))
{
}
This approach probably isn't very "straightforward", but it makes it harder to miss a combination.
But yeah... it isn't great. I just haven't really figured out a better way to do it.