Reputation:
I would like to know if this is a good idea that to implement simple 2D collision detection of rectangles as follows:
Collision col = new Rectangle();
<- Should I do that or is that something that should be avoided? I am aware that I 'can' but should I?contains()
and intersects()
methods; should I be doing that or should I be doing something else for 2D collision detection in Java?Upvotes: 3
Views: 2689
Reputation: 17853
What about making it unrelated to Rectangle in the first place? Make a new, standalone Collision module and handle any different types you want.
(I don't know Java, sorry for any issues here)
class Collision
{
public boolean BetweenRectangles(Rectangle a, Rectangle b)
{
}
public boolean BetweenCircles(Circle a, Circle b)
{
}
public boolean RectangleToCircle(Rectangle r, Circle c)
{
}
public boolean MyCrazyShapeToRectangle(MyCrazyShape mcs, Rectangle r)
{
}
}
IMHO it doesn't really make sense to make a collision out of a rectangle because a collision is an orthogonal concept to the rectangle, and jamming them together needlessly constrains your future options. The key thing to realize is that you don't really need a collision object, per se, these functions are procedural by nature (does Java have something like C++'s 'static' modifier for class-scope member functions?). The collision itself isn't a property of either of the participants of a collision.
Upvotes: 0
Reputation: 133577
you can easily extend Rectangle
class CollidableRectangle extends Rectangle
{
public boolean isCollidingWith(Rectangle otherRect)
{
//check collision
}
// return all collisions
public List<CollidableRectangle> getCollisions(List<Rectangle)
{
// code
}
}
then you would use it like:
CollidableRectangle r1 = new CollidableRectangle();
CollidableRectangle r2 = new CollidableRectangle();
r1.isCollidingWith(r2);
//and so on
As noted in comments I didn't use a Collision
class. Usually you need it because you are also interested in collision parameters like depth or colliding plane so you would have something like:
class Collision
{
CollidableRectangle first, second;
float depth;
Line2D collidingLine;
}
and the method would return a list of collisions:
public List<Collision> getCollisions(List<Rectangle) { ... }
Upvotes: 2
Reputation: 43487
There is not a is-a
relation between a Collision and a Rectangle, a collision is not a rectangle. A collision domain may have rectangles which suggests that you use composition.
Upvotes: 7