well I am attempting to move a ship like in asteroids. my question is how do I move a figure ship that follows its nose. it now moves strictly up and down. here is my code.
#include<freeglut.h>
#include<iostream>
#include<math.h>
using namespace std;
float shipenemyAngle = 0.0f;
float shipAngle = 0.0f;
float thrust = 0.0f;
const float PI = 3.1415926;
void drawShip()
{
glPushMatrix();
glColor3f(1.0f, 0.0f, 0.0f);
glTranslatef(50.0f, 0.0f, 0.0f);
glBegin(GL_LINE_LOOP);
float offsets[4][2] = { {0.0f, 0.0f}, {-5.0f, -5.0f}, {0.0f, 10.0f}, {5.0f, -5.0f} };
float cosA = cos(shipAngle);
float sinA = sin(shipAngle);
for (int i = 0; i < 4; i++)
glVertex3f(offsets[i][0] * cosA - offsets[i][1] * sinA, offsets[i][0] * sinA + offsets[i][1] * cosA, 0.0f);
glEnd();
glPopMatrix();
}
void drawEnemyShip()
{
glPushMatrix();
glColor3f(0.0f, 1.0f, 0.0f);
glLoadIdentity();
glTranslatef(-50.0f, 0.0f, 0.0f);
glRotatef(shipenemyAngle, 0.0f, 0.0f, 1.0f);
glBegin(GL_LINE_LOOP);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(-5.0f, -5.0f, 0.0f);
glVertex3f(0.0f, 10.0f, 0.0f);
glVertex3f(5.0f, -5.0f, 0.0f);
glEnd();
glPopMatrix();
}
void renderScene()
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
drawShip();
drawEnemyShip();
glPopMatrix();
glutSwapBuffers();
}
void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat aspectRatio;
if (h == 0)
h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
aspectRatio = (GLfloat)w / (GLfloat)h;
if (w <= h)
glOrtho(-100.0, 100.0, -100.0 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0);
else
glOrtho(-100.0*aspectRatio, 100.0*aspectRatio, -100.0, 100.0, 1.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void handleKeypress(unsigned char key, int x, int y)
{
switch (key)
{
case 27:
exit(0);
break;
case 'a':
shipenemyAngle+=PI/8;
break;
case 'd':
shipenemyAngle-=PI/8;
break;
case 'w':
break;
case 'x':
break;
}
glutPostRedisplay();
}
void handleSpecialKeypress(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
shipAngle+=PI/8;
break;
case GLUT_KEY_RIGHT:
shipAngle-=PI/8;
break;
case GLUT_KEY_UP:
glTranslatef(0.0f, 1.0f, 0.0f);
break;
case GLUT_KEY_DOWN:
glTranslatef(0.0f, -1.0f, 0.0f);
break;
}
glutPostRedisplay();
}
int main(int argc, char**argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowPosition(600, 400);
glutInitWindowSize(800, 600);
glutCreateWindow("Space Wars");
glutDisplayFunc(renderScene);
glutKeyboardFunc(handleKeypress);
glutSpecialFunc(handleSpecialKeypress);
glutReshapeFunc(ChangeSize);
glutMainLoop();
}