Please help with my C++ OpenGL code!
I am trying to make a simple game in OpenGL with C++ (my first). The issue I'm having is that the WSAD keys move the sphere AND the cube. Since the goal of the game is going to be to get points by placing the sphere over the cube, how would I make the sphere move all by itself? glTranslatef() is moving both at the same time, and I don't know how to tell it to move only one. Although that is my main/largest problem, I was also wondering two more things. How do I overlay text, so I could show the user the elapsed time and their score? Also, how do I make the sphere move smoothly, as opposed to going one pixel, stopping, then going again when you hold down a key? Right now I'm using SPI_SETKEYBOARDDELAY, but it's not working well at all. Thanks for all the help!
P.S.: If you provide code, could you please explain it? Also, could someone explain glutPostRedisplay, glutIdleFunc, glutMainLoop, glPushMatrix, glPopMatrix, and glutSwapBuffers? Thanks everyone!
#include <glut.h>
#include <cmath>
#include <time.h>
#include <string>
using namespace std;
int genrandom();
GLfloat tplayer;
GLfloat tobject;
double angle = 0;
double angleadd = 0.2;
int c = 0;
int d = 0;
int random;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(angle, 0, 0.5, 1);
glColor3f (0, 0.2, 1);
glutWireSphere(5, 10, 10);
glPopMatrix();
glPushMatrix();
glTranslatef(10, 10, 0);
glRotatef(angle, 0, 0.5, 1);
glColor3f (1, 0, 0);
glutWireCube(3);
glPopMatrix();
glutSwapBuffers();
}
int genrandom(){
srand ( time(NULL) );
random = rand() % 95 + -95;
return random;
}
void KeySet() { DWORD old = 0;
SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &old, 0);
SystemParametersInfo(SPI_SETKEYBOARDDELAY,0, &old, 0);
}
void keyboard(unsigned char key, int x, int y)
{
KeySet();
if(key == 27) exit (0);
else if( (key == 119) && (95 > d) ){
glTranslatef(0, 1, 0);
d = d + 1;
}
else if( (key == 115) && (d > -95) ){
glTranslatef(0, -1, 0);
d = d - 1;
}
else if( (key == 97) && (c > -95) ){
glTranslatef(-1, 0, 0);
c = c - 1;
}
else if( (key == 100) && (95 > c) ){
glTranslatef(1, 0, 0);
c = c + 1;
}
}
void idle()
{
angle += angleadd;
glutPostRedisplay();
}
int main (int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (800, 800);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Space Journey");
glClearColor (0, 0, 0, 0);
glColor3f (1, 1, 1);
glEnable (GL_DEPTH_TEST);
glMatrixMode (GL_MODELVIEW);
glOrtho(-100, 100, -100, 100, -100, 100);
glutDisplayFunc (display);
glutKeyboardFunc (keyboard);
glutIdleFunc (idle);
glutFullScreen ();
glutMainLoop ();
return 0;
}