0

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.

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
user2622574
  • 293
  • 1
  • 3
  • 9
  • 2
    No. Don't use `Object`, poor practice. Create a base class, I've designed EVERYTHING, there's always a way. – jiveturkey May 23 '17 at 17:07
  • 1
    Take 2 hours and read the relevant parts of "Game Programming Patterns" (Nystrom, 2014). He discusses some concepts about classes for game objects and their interactions that you may find very useful. – KevinO May 23 '17 at 17:10

2 Answers2

3

Well, if you wanted, you could do something like this to get the pos.x of the object

((Player)a).pos.x

But, again, while this may suffice your needs, I would suggest making an interface,like

public interface GameObject{
    public Vector3 getPosition();
}

and making all of the "Game Objects" implement it, and then do

boolean doCollide (GameObject a, GameObject b)

Not only the first way is bad practice, but makes debugging at compile time harder, which generally is a bad sign.

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
3

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Enemy, Player and Obstacle classes probably share many things in common, methods like getPosition() which most likely just returning positions could be implemented in parent class and only specific method which doing rendering/updating/moving or any action should be implemented in these classes. – eldo May 24 '17 at 07:16