mardi 24 mars 2020

Use of reflection in Java. Is there a better way to do this?

I've decided to try to create a simple game engine and I appear to be stuck on how to efficiently check for collisions between different Collider types for my game objects. For example, some game objects may use a SphereCollider and others may use an AABBCollider, both of which extend the Collider class.

Here is the code within my GameObject class.

public final boolean collidesWith(Collider c) {
    if (this.collider instanceof Collider3D) {
        if (c instanceof AABBCollider3D) {
            if (((Collider3D) this.collider).collidesWith((AABBCollider3D) c))
                return true;
        } else if (c instanceof SphereCollider3D) {
            if (((Collider3D) this.collider).collidesWith((SphereCollider3D) c))
                return true;
        } else if (c instanceof AABBCollider2D) {
            if (((Collider3D) this.collider).intersects((AABBCollider2D) c))
                return true;
        }
    } else if (this.collider instanceof Collider2D) {
        // Do 2D collision stuff...
    }
}

I would like to know if there is a better way of doing this, mainly for two reasons:

  1. I've heard using reflection to check object types in this way is a workaround for bad code design
  2. Adding custom Collider types in the future would require me to extend the logic here, as well as in my Collider class




Aucun commentaire:

Enregistrer un commentaire