I Need Simple Movement with WASD key input

Hello. I am completely new to this site, as I have registered only 20 minutes ago. I started C++ about 3 weeks ago, printed out and read the tutorial, and know only the very basics of programming. I use a Mac and an older version of Xcode, version 3.2.

Right now, I am trying to attempt to make a triangle I made using OpenGL and GLUT move accordingly up, left, down and right to the WASD keys (respectively).
Following a video tutorial on YouTube, I managed to make a colorful triangle on OpenGL using GLUT. I decided to go further and make it move.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <GLUT/GLUT.h>

void render(void);

void keyboard(unsigned char c, int x, int y);

void mouse(int button, int state, int x, int y);

int main(int argc, char** argv) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(640, 480);
	glutCreateWindow("My First GLUT Application");
	
	glutDisplayFunc(render);
	glutKeyboardFunc(keyboard);
	glutMouseFunc(mouse);
	
	glutMainLoop();
}

void keyboard(unsigned char c, int x, int y) {
	if (c==27) {
		exit(0);
	}	
}

void mouse(int button, int state, int x, int y) {
	if (button == GLUT_RIGHT_BUTTON) {
		exit(0);
	}
}

void render(void) {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	glBegin(GL_TRIANGLES);
		glColor3f(1, 0, 0);
		glVertex2f(-0.5, -0.5);
		glColor3f(0, 1, 0);
		glVertex2f(0.5, -0.5);
		glColor3f(0, 0, 1);
		glVertex2f(0.0, 0.5);
	glEnd();
	
	glutSwapBuffers();
}

I am terribly sorry for posting such a giant amount of code (I read the sticky about posting topics here and long lines of code) but couldn't think of any other way to post it without showing what I wanted.

Right now it is programmed so that the window would close if I clicked the right mouse button or the Esc button.


I would store x and y variables for the position as global vars, and in the keyboard callback I would increment/decrement these accordingly. Then, in the render-function you need to use glTranslate (I think) with the x and y vars before the call to glBegin. This is assuming that you are only working with motion in 2d (only moving up/down and left/right on the screen).

Also, respect for doing openGL-stuff after only three weeks of C++ :)
Topic archived. No new replies allowed.