Search code examples
javaprocessing

Any ideas on how i could create a "Object collision detection" with the code i have here?


Im trying to make a game were if the main character (gubbe) collides with the enemy (fiende) the character will take damage(Healthdisplay/HW). ive tried to make a collision detection thing in many ways, mainly if(x.intersects(y)){}. Im stuck and don't know how to solve it. ill put the main code down here VVV. if more code is needed just say and ill put in the needed code.

HW is the hp-pool were the damage should be done to.

void display is were the main character/rectangle is created.

the enemy is in another page in processing.

class gubbe {

    float x = 0;
    float y = 0;
    int HW = 20;
    //rect sidor
    int h1 = 100;
    int w1 = 100;
    //----

    //VV movement VV
    void move() {

    if (keyPressed) {
        if (key == 'w' || key == 'W') {
            //terms, move forward, Y-led.
            y -= 100;
        }
    }
    if (keyPressed) {
        if (key == 'a' || key == 'A') {
            //terms, move right, X-led.
            x -= 100;
        }
    }
    if (keyPressed) {
        if (key == 's' || key == 'S') {
            //terms, move backwards, Y-led.
            y += 100;
        }
    }
    if (keyPressed) {
        if (key == 'd' || key == 'D') {
            //terms, move left, X-led.
            x += 100;
        }
    }
}

// VV visual VV
void display() {
    //Grabb
    fill(127);
    stroke(0);
    rect(x, y, w1, h1);
}

void display2() {
    fill(127);
    stroke(0);
    rect(x, y, w1, h1);
}

// VV Edgechechning VV
void checkEdges() {
    if (x + 100 > width) {
        x -= 50;
    } else if (x < 0) {
        x += 50;
    } else if (y > height) {
        y -= 50;
    } else if (y < 0) {
        y += 50;
    } else {
    }
}

// VV Fighting VV
void Fight() {
    if (keyPressed) {

        if (key == 'm'|| key == 'M') {
            //villkor, flytta höger, X-led.
            fill(255, 0, 0);
            stroke(255, 0, 0);
            rect(x, y-100, 100, 100);
        }
    }
}

// VV  health bars VV
void BarsDisplay() {
    fill(204, 204, 204);
    stroke(204, 204, 204);
    rect(x, y-30, 100, 9);
}

void HealthDisplay() {
    fill(0, 0, 255);
    stroke(255, 0, 0);
    rect(x, y-31, HW, 3);
    !!! here there should be collision detection!!!

}

void XpDisplay() {
    fill(255, 255, 0);
    stroke(255, 255, 0);
    rect(x, y-22, 2, 1);
    //if(om dödar fiende){
    //  width+=x
    //}
    //else{
    //}
}
}

Solution

  • Your Objects seem to be in rectangular shape, so a collision takes place if the distance between both centers along the x-axis as well as the y-axis is smaller than half the size of each object in direction of that axis added up.

    Take a piece of paper and sketch it down, then you will see it!