Collision 2D Quads
Posted
by
Vico Pelaez
on Game Development
See other posts from Game Development
or by Vico Pelaez
Published on 2012-11-02T15:10:05Z
Indexed on
2012/11/02
17:33 UTC
Read the original article
Hit count: 243
I want to detect collision between two 2D squares, one square is static and the other one moves according to keyboard arrows. I have implemented some code, however nothing happens when they overlap each other and what I tried to achieve in the code was to detect an overlapping between them. I think I am either not understanding the concept really well or that because one of the squares is moving this is not working. Please I would really appreciate your help. Thank you!
float x1=0.05 ,Y1=0.05;
float x2=0.05 ,Y2=0.05;
float posX1 =0.5, posY1 = 0.5;
float movX2 = 0.0 , movY2 = 0.0;
struct box{
int width=0.1;
int heigth=0.1;
};
void init(){
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1.0, 1.0, 1.0);
}
void quad1(){
glTranslatef(posX1, posY1, 0.0);
glBegin(GL_POLYGON);
glColor3f(0.5, 1.0, 0.5);
glVertex2f(-x1, -Y1);
glVertex2f(-x1, Y1);
glVertex2f(x1,Y1);
glVertex2f(x1,-Y1);
glEnd();
}
void quad2(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glPushMatrix();
glTranslatef(movX2, movY2, 0.0);
glBegin(GL_POLYGON);
glColor3f(1.5, 1.0, 0.5);
glVertex2f(-x2, -Y2);
glVertex2f(-x2, Y2);
glVertex2f(x2,Y2);
glVertex2f(x2,-Y2);
glEnd();
glPopMatrix();
}
void reset(){
//Reset position of square???
movX2 = 0.0;
movY2 = 0.0;
collisionB = false;
}
bool collision(box A, box B){
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate the sides of box A
leftA = x1;
rightA = x1 + A.width;
topA = Y1;
bottomA = Y1 + A.heigth;
//Calculate the sides of box B
leftB = x2;
rightB = x2 + B.width;
topB = Y1;
bottomB = Y1+ B.heigth ;
if( bottomA <= topB ) return false;
if( topA >= bottomB ) return false;
if( rightA <= leftB ) return false;
if( leftA >= rightB ) return false;
return true;
}
float move_unit = 0.1;
void keyboardown(int key, int x, int y)
{
switch (key){
case GLUT_KEY_UP:
movY2 += move_unit;
break;
case GLUT_KEY_RIGHT:
movX2 += move_unit;
break;
case GLUT_KEY_LEFT:
movX2 -= move_unit;
break;
case GLUT_KEY_DOWN:
movY2 -= move_unit;
break;
default:
break;
}
glutPostRedisplay();
}
void display(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
cuad1();
if (!collision) {
cuad2();
}
else{
reset();
}
glFlush();
}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Collision Practice");
glutSpecialFunc(keyboardown);
glutDisplayFunc(display);
init();
glutMainLoop();
}
© Game Development or respective owner