# Collision Responses with many different types

I'd like to write an efficient Collision Response code, that does not use instanceof/type checks that often (if possible)

my current implementation is something like this:

GameObject.collidesWith(GameObject other)
{
if(other instanceof ConcreteType1)
{
//do response with Concrete Type 1
}else if (other instanceof ConcreteType2)
// do response with Concrete Type 2
}
}


GameObject is the base class of everything. Is there a possibility to avoid instanceof and type checks?

• Make base classes like, BasicConcrete, then all new Concrete must extend this class, unless if you want different behavior for each concrete type – DH. Jan 20 '16 at 11:12
• What is your requirement about this? Why don't you want to use instanceof? What language are you using? – Alexandre Vaillancourt Jan 21 '16 at 4:29
• Take a look at en.wikipedia.org/wiki/Double_dispatch , maybe you can use this idiom in your programming language. – Exilyth Feb 19 '16 at 18:59

This is the part I currently need to work on for my own game..

What I've reasoned out so far is that I can have a CollisionBox on the GameObject which contains all the collision boundary information. Collisions are checked by GameObject.isColliding(other) - where the two CollisionBoxes compare whether they intersect.

if (gameObject.isColliding(other))
{
gameObject.doCollision(other);
}


then the GameObject has a doCollision method which is overridden for various GameObjects

public GameObject
{
CollisionBox collisionBox;
CollisionType collisionType;

public void doCollision(GameObject other)
{
switch(other.CollisionType)
{
case Inelastic: //etc
case Elastic: //etc
case Consumable: //(this one is for bullets, upgrades, pickups -
// things you collide with but the collision doesn't affect motion)
}
}
}


As you can maybe guess, CollisionType is an enum which is assigned to GameObject.

That was my initial plan anyway. Now I hope to take some inspiration from Collision detection and response in an Entity System - though I'll still probably end up with some type of "collisionType enum" to broadly group a type of collision.