Help with crash detection

So i have a game i have a defender and aliens who are moving towards the defender and the defender is the user who avoids the alien. I need to add a collision detection so when the alien collides with the defender the game can end. I know that i need some sort of for loop to repeat a block of actions a certain amount number of times and i can detect a collision using color test = get(x,y); and then if (test==Alien1) would someone be able to help me implement and explain to me how i can do this. Many thanks. here is my code below

class Defender {
    int x, y;

    Defender(int x, int y) {
        this.x = x;
        this.y = y;
    }

    void render() {
        //draw a defender
        fill(255, 0, 0);
        rect(x, y, 50, 20);
        triangle(x + 50, y, x + 50, y + 20, x + 60, y + 10);
        fill(0, 0, 100);
        rect(x, y - 10, 20, 10);
    }

    boolean crash() {
        return true;
    }
}


    PImage background;
    int x = 0; //global variable background location

    Alien alien1;
    Alien alien2;
    Alien alien3;

    Defender user1;


    void setup() {
        size(800, 400);
        background = loadImage("spaceBackground.jpg");
        background.resize(width, height);

        alien1 = new Alien(800, 100, 5);
        alien2 = new Alien(800, 200, 5);
        alien3 = new Alien(800, 300, 5);

        user1 = new Defender(10, height / 2);

    }

    void draw() {
        drawBackground();
        alien1.move();
        alien1.render();
        alien2.move();
        alien2.render();
        alien3.move();
        alien3.render();
        user1.render();
    }


    void drawBackground() {
        image(background, x, 0); //draw background twice adjacent
        image(background, x + background.width, 0);
        x -= 4;
        if (x == -background.width)
            x = 0; //wrap background
    }

    void keyPressed() {

        if (key == CODED) {
            if (keyCode == UP) {
                user1.y = user1.y - 5;
            } else if (keyCode == DOWN) {
                user1.y = user1.y + 5;
            }
        }


    }
1 Like

You could put it in void draw() for the void loop, and maybe do something like this

void draw() {
background(whatever colour you're using);
//put collision detection here
if(collided) { //or, if Alien1/whatever boolean you choose
endGame();
}

void endGame() {
//put code here
//for when the player has collided
}

For an overview of collision detection in Processing, see either the Happy Coding guide or Thompson’s http://www.jeffreythompson.org/collision-detection/