Simple AAB collision in 2D game using glrectf

  2d-games, c++, collision, collision-detection, math

I have been trying to implement a basic 2d collision system inside my game. This game consists of a primitives drawn using glrectf() and I am trying to make a game where you move around and avoid touching the obstacles. if you touch the obstacles points are removed. Currently I’m trying to implement some kind of collision and I cannot get it to work. I have tried storing the xmin,ymin,xmax,ymax values into a vector to then iterate through and compare positions to enemy obstacles but the vector does not seem to update the positions Any help regarding this would be super helpful and much appreciated!
This is my current code for struct collision, my player(car), obstacles, collision function

 struct AxisAlignedBox{
    GLfloat m_xmin, m_ymin;
    GLfloat m_xmax, m_ymax;
    GLfloat m_width, m_height;
    AxisAlignedBox(GLfloat xmin, GLfloat ymin, GLfloat xmax, GLfloat ymax, GLfloat width, GLfloat height )
    {
        m_xmin = xmin;
        m_ymin = ymin;
        m_xmax = xmax;
        m_ymax = ymax;
        m_width = width;
        m_height = height;
    }
};

std::vector<AxisAlignedBox> box;
std::vector<AxisAlignedBox> playerBox

    void car()
{
    GLfloat x1 = 30;
    GLfloat y1 = 100;
    GLfloat x2 = 120;
    GLfloat y2 = 130;
    glColor3f(0.5, 0.7, 0.3);
    glPushMatrix();
    glTranslatef(xmove, ymove, 0);
    glRectf(x1, y1, x2, y2);
    glPopMatrix();
    glFlush();
    
    playerBox.push_back(AxisAlignedBox(x1,y1,x2,y2, 120, 60));
//    for(AxisAlignedBox x: playerBox)
//        std::cout << x << std::endl;
}

    void obstacles()
{

    glColor3f(1.0, 0, 0);
    srand(0);
    GLfloat x1, y1, x2, y2;
    x1 = 160;
    y1 = 230;
    x2 = 210;
    y2 = 280;
    for(int count = 0; count < 7; count++)
    {
        glPushMatrix();
        GLfloat xpos = rand() % 300 + 1;
        GLfloat ypos = rand() % 300 + 1;
        glTranslatef(xpos, ypos, 0.0);
        glRectf(x1, y1, x2, y2);
        AxisAlignedBox obstaclebox(x1, y1, x2, y2, 100, 100);
        box.push_back(obstaclebox);
        glPopMatrix();
    }
    glFlush();
}


   void doCollision()
{
    for(int i = 0; i < playerBox.size(); i++) {
                for(int j = 0; j < box.size(); j++)
                {
                    if(playerBox[i].m_xmin + playerBox[i].m_width > box[j].m_xmin &&
                       playerBox[i].m_xmin < box[j].m_xmin + box[j].m_width &&
                       playerBox[i].m_ymin > box[j].m_xmin &&
                       playerBox[i].m_ymin < box[j].m_ymax)
                    {
                        std::cout << "Collided" << std::endl;
                    }
                }
            }
}

Source: Windows Questions C++

LEAVE A COMMENT