Feb 6, 2014 at 12:46pm UTC
Hello guys. I wanna make the body (square) move left when I press the left arrow key. Unfortunately, it's in data structures and I don't know what to put in the "void SpecialKeys(int key, int x, int y)" part to make it move. Any help would be good. :) By the way, I'm just a beginner. Our prof explain this but it's still kind of a blur and I wanna learn as much as possible. Cheers!
#include <vector>
#include <time.h>
using namespace std;
#include "Glut_Setup.h"
struct Vertex
{
float x,y,z;
};
Vertex Body []=
{
(-0.5, -2, 0),
(0.5, -2, 0),
(0.5, -3, 0),
(-0.5, -3, 0)
};
void GameScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(-0.5, -2, 0);
glVertex3f(0.5, -2, 0);
glVertex3f(0.5, -3, 0);
glVertex3f(-0.5, -3, 0);
glEnd();
glutSwapBuffers();
}
void Keys(unsigned char key, int x, int y)
{
switch(key)
{
}
}
void SpecialKeys(int key, int x, int y)
{
switch(key)
{
}
}
Feb 6, 2014 at 1:52pm UTC
Hi Adriyel,
here you are using the GLUT library as opposed to just OpenGL.
One of the ways GLUT helps you here is that it provides defines for your input keys allready:
GLUT_KEY_LEFT
GLUT_KEY_UP
GLUT_KEY_RIGHT
GLUT_KEY_DOWN
these are defined in the glut.h header
for something bigger you would want to write a more advanced input handler but for this its good enough to just add a some cases to your switch.
1 2 3 4 5
switch (key)
{
case GLUT_KEY_LEFT:
break ;
}
Last edited on Feb 6, 2014 at 2:10pm UTC
Feb 6, 2014 at 1:59pm UTC
for moving the square, there are two ways to do it, a right way and a wrong way.
In theory you can store a variable for your x_offset and just add to it every time the user has pressed the left key.
then in this block:
1 2 3 4 5 6 7
glBegin(GL_QUADS);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(-0.5, -2, 0);
glVertex3f(0.5, -2, 0);
glVertex3f(0.5, -3, 0);
glVertex3f(-0.5, -3, 0);
glEnd();
you could just add your xoffset to each x value
1 2 3 4 5 6 7
glBegin(GL_QUADS);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(x_offset+ -0.5, -2, 0);
glVertex3f(x_offset+ 0.5, -2, 0);
glVertex3f(x_offset+ 0.5, -3, 0);
glVertex3f(x_offset+ -0.5, -3, 0);
glEnd();
BUT the more "correct" method is to use the OpenGL transforms.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
glPushMatrix();
glLoadIdentity ()
glTranslatef(x_offset, 0.0f, 0.0f)
glBegin(GL_QUADS);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(x_offset+ -0.5, -2, 0);
glVertex3f(x_offset+ 0.5, -2, 0);
glVertex3f(x_offset+ 0.5, -3, 0);
glVertex3f(x_offset+ -0.5, -3, 0);
glEnd();
glPopMatrix();
I hope this helps, thanks -NGangst
Last edited on Feb 6, 2014 at 2:10pm UTC