In want to check whether two items collide in space. For that purpose both items are represented by some simplified geometric shapes - for simplicity lets assume these shapes can only be circles, polygons and lines. The items can be represented by any of these shapes and the collision-detection needs to be able to handle any of the possible combinations. I want to find a strategy that involves minimal code duplication and allows adding further shapes in the future.
My approach is the following:
public class Item{
private Collidable bounds;
public boolean checkCollision(Item target){
return bounds.checkCollision(target.getBounds());
}
}
Where Collidable is the interface for any geometric shape and a possible shape would look like:
public class Circle implements Collidable{
public boolean checkCollision(Collidable target){
if(target instanceof Cirlce){
//Algorithm for circle-circle collision
}else if(target instanceof Line){
//Algorithm for circle-line collision
//...
}else{
return false;
}
}
}
This however yields a lot of code duplication (the same circle-line collision algorithm would need to be repeated in the Line class) and does not seem elegant. I looked into different design patterns in search of a solution, but only ended up with this strategy-like solution. What would be a better approach here?
Aucun commentaire:
Enregistrer un commentaire