(opengl, c++) Functions and data structures in a square and rectangle

Hi guys. I have a square at the top and a small rectangle at the bottom that can be moved through the the 'a' (left) and 'd' (right) keys. When I move the square to the right, the rectangle goes left, vice versa. My question is, how do I convert my points (head1x, leg1x, etc) and the movement of the shapes ( head1x=head1x+1;) into functions, then into data structures? If possible, it would be nice if someone could also show me why you did this, did that, etc. Thank you very much! :) Note: head= square, leg=rectangle. :) My professor doesn't really explain well all she ever said was that functions and data structures make long codes shorter but I don't really understand why. Thank you. :)

Here's the code:

#include <vector>
#include <time.h>

using namespace std;

#include "Glut_Setup.h"

float
head1x= -0.5, head1y=3, head1z=0,
head2x= 0.5, head2y=3, head2z=0,
head3x= 0.5, head3y=2, head3z=0,
head4x= -0.5, head4y=2, head4z=0;


float
leg1x=-0.6, leg1y=-2, leg1z=0,
leg2x=-0.4, leg2y=-2, leg2z=0,
leg3x=-0.4, leg3y=-3, leg3z=0,
leg4x=-0.6, leg4y=-3, leg4z=0;






void GameScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);



glBegin(GL_QUADS);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(leg1x, leg1y, leg1z);
glVertex3f(leg2x, leg2y, leg2z);
glVertex3f(leg3x, leg3y, leg3z);
glVertex3f(leg4x, leg4y, leg4z);
glEnd();



glBegin(GL_QUADS);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(head1x, head1y, head1z);
glVertex3f(head2x, head2y, head2z);
glVertex3f(head3x, head3y, head3z);
glVertex3f(head4x, head4y, head4z);
glEnd();


glutSwapBuffers();


}

void Keys(unsigned char key, int x, int y)
{
switch(key)
{
case 27 : exit(0); break;
case 'a':
{

head1x=head1x-1;
head2x=head2x-1;
head3x=head3x-1;
head4x=head4x-1;

leg1x=leg1x+1;
leg2x=leg2x+1;
leg3x=leg3x+1;
leg4x=leg4x+1;




break;

}

case 'd':
{

head1x=head1x+1;
head2x=head2x+1;
head3x=head3x+1;
head4x=head4x+1;

leg1x=leg1x-1;
leg2x=leg2x-1;
leg3x=leg3x-1;
leg4x=leg4x-1;


break;
}
}
}

void SpecialKeys(int key, int x, int y)
{
switch(key)
{


}
}

void Timer(int value)
{
glutTimerFunc(50, Timer, value);
glutPostRedisplay();
}

void changeSize(int w, int h)
{
float ratio = 1.0 * w / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(45, ratio, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 30.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}

void main(int argc, char **argv)
{
srand(time(NULL));
GLUTInit(&argc, argv);
}
Topic archived. No new replies allowed.