I have to refactor my code but dont know where to put the collision method

I don't speak English, so please bear with me and my English. I made a space invaders game with collision techniques. For when bullets hit walls or enemies, where should they be? Should I create a completely new class for them, or just place the collision methods somewhere with the Enemy class and the Wall class?

It is currently a collision method in my Enemy class to show you what I mean and what I am doing. I am trying to make code that is clean and readable that can be easily reused.

 public boolean collide(int i, Player player, BasicBlocks blocks,
        ArrayList<EnemyTypeBasic> enemies) {
    if (enemySprite.isPlay()) {
        if (enemies.get(i).deathScene()) {
            enemies.remove(i);

        }
        return false;
    }
    for (int w = 0; w < player.playerWeapons.weapons.size(); w++) {
        if (enemies != null
                && player.playerWeapons.weapons.get(w).collisionRectangle(
                        ((EnemyTypeBasic) enemies.get(i)).getRect())) {
            enemySprite.resetLimit();
            enemySprite.setAnimationSpeed(120);
            enemySprite.setPlay(true, true); // Object needs to be destroyed
            GameScreen.SCORE += 8;
            GameScreen.lives = 3;
            return true;
        }
    }
    return false;
}

      

Thank you very much!

+3


source to share


1 answer


What objects can collide? If the only collisions are between bullets and other objects, your collide () method belongs to the class representing the markers.

What I think is more likely, and will be more beneficial in the long run, is that you will have several things to collide with. Bullets might collide with ships, but you might end up wanting the ships to collide with other ships or with walls. In that case it would be wise to define an abstract class like this

public abstract class Collidable {

    public boolean collide(Collidable other) {
        // Here is your logic to check whether *this* is colliding with *other*
        // You will probably need to pass in additional arguments to determine collisions
    }

}

      

Then all types that might collide with others extend your abstract class, for example:



public Player extends Collidable {
    // ...
}

public EnemyTypeBasic extends Collidable {
    // ...
}

public Bullet extends Collidable {
    // ...
}

      

and if you want to check if two things collide, you can simply call it, or equivalent:

aBullet.collide(anEnemy)

      

0


source







All Articles