I am making a simple game about shooting enemies and avoiding obstacles, but I have a problem with detecting collisions because I’ve got a lot of classes for every type of game object (player,enemy,obstacle,drop,bullet, etc.).
class Player { Vector3 pos; ... } class Enemy { Vector3 pos; ... } class Obstacle { Vector3 pos; ... } ... boolean doCollide (Object a, Object b) { if ( a.pos.x + a.size.w >= b.pos.x ) { ... } ... }
And it won’t work because a doesn’t have ‘pos’, etc, so how can I do it so it works for every class? I’ve read about interfaces but I don’t really know how can it help me.
Advertisement
Answer
You could cast the Object
types to your own types, However considering that there are multiple custom object types, attempting to take that approach is not efficient therefore you can use an interface.
Interface declaration:
public interface IsomeName{ public Vector3 getPosition(); }
your classes:
class Player implements IsomeName{ @Override public Vector3 getPosition(){...}}; class Enemy implements IsomeName{ @Override public Vector3 getPosition(){...}} class Obstacle implements IsomeName{ @Override public Vector3 getPosition(){...}}
then your doCollide
will become:
boolean doCollide (IsomeName a, IsomeName b) { ... ... ... }
Another option would be to create an abstract base class with an abstract getPosition()
method and let each type provide their own implementations of it.