I'm programming a simple asteroid game in Java. And find this problem (not really a problem, my solution works perfectly, but looks ugly). I just want to know is there a way to simplify my code.
There are some objects in my game. Ship, Meteor, Bullet, and Coin. All of them are a subclass of GameObject. To handle collisions, in the MyGame class I have these functions.
private void ship_hit_meteor(Ship ship, Meteor meteor){}
private void bullet_hit_meteor(Bullet bullet, Meteor meteor){}
private void ship_hit_coin(Ship ship, Coin coin){}
//...and so on
For collision-checking, I put all of the objects in 1 big objArray. Then I iterate the array to check the collisions. This is how I do it: But imagine if I have 100 types of objects.
//inside the collision loop
GameObject a = objArray[i];
GameObject b = objArray[j];
if(a instanceof Ship && b instanceof Meteor ){
ship_hit_meteor((Ship)a, (Meteor)b);
}
else if(a instanceof Meteor && b instanceof Ship){
ship_hit_meteor((Ship)b, (Meteor)a);
}
else if(a instanceof Bullet && b instanceof Meteor){
bullet_hit_meteor((Bullet)a, (Meteor)b);
}
else if(a instanceof Meteor && b instanceof Bullet){
bullet_hit_meteor((Bullet)b, (Meteor)a);
}
//... end of the loop
Is there any way to simplify this?
Thanks.