Search code examples
javaopenglcollision-detection

Collision detection - avoid box


I'm making a racing car game where my racing course is similar to a rectangular donut. In the middle of the rectangle I have another smaller rectangle which acts as a wall. I'm trying to add collision detection to my inside wall so that my cars will collide with the inside walls. Below are some basic measurements of the inside wall as well as a picture showing a concept of the track:

-Translated x from 14 to 18 units is the width of the rectangle.

-Translate y from -60 to 60 units is the total length of the rectangle.

My problem currently is if I try making the cars collide when the x position hits the wall at 14 units from the origin (or with y), it creates collision for the entire x or y line. So for example, once I hit the wall that's located 14 units in the x direction it doesn't let me pass if I were to reach that location at one of the turning points in the race course. I'm trying the following at the moment.

void checkColl(){
    if (posX < -14){
         velocityX *= -1 //bounce off the wall on the far left side of the picture
    }
    if (posX > 48){
        velocityX *= -1 //bounce off wall on far right
    }
    if ((posY > 60 || posY < -60) && (posX > 14 && posX < 18)){ //bounce off the rectangle in middle of race course
        velocityY = velocityY * -1;
        velocityX = velocityX * -1;
    }
}

enter image description here


Solution

  • The check for the y coordinate is broken. Try this:

    if ((posY > -60 && posY < 60) && (posX > 14 && posX < 18)){
            //bounce off the rectangle in middle of race course
    

    This defines points within the black rectangle - the hole of the "doughnut".