FPS Game
FPS Game
h>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <ctime>
// Movement variables
// Target structure
struct Target {
float x, y, z;
bool active;
};
std::vector<Target> targets;
// Bullet structure
struct Bullet {
float x, y, z;
bool active;
};
std::vector<Bullet> bullets;
// Score
int score = 0;
void initTargets() {
srand(time(0));
Target t;
t.active = true;
targets.push_back(t);
glPushMatrix();
glTranslatef(x, y, z);
glutSolidCube(0.5f);
glPopMatrix();
glTranslatef(x, y, z);
glPopMatrix();
void drawCrosshair() {
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glBegin(GL_LINES);
// Horizontal line
glVertex2f(48, 50);
glVertex2f(52, 50);
// Vertical line
glVertex2f(50, 48);
glVertex2f(50, 52);
glEnd();
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
void fireBullet() {
Bullet b;
b.x = cameraX;
b.y = cameraY;
b.z = cameraZ;
b.active = true;
bullets.push_back(b);
void updateBullets() {
if (!bullets[i].active) {
bullets.erase(bullets.begin() + i);
continue;
}
bullets[i].x += bullets[i].dx;
bullets[i].y += bullets[i].dy;
bullets[i].z += bullets[i].dz;
if (targets[j].active &&
targets[j].active = false;
bullets[i].active = false;
score++;
break;
bullets[i].active = false;
i++;
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Draw ground
glBegin(GL_QUADS);
glEnd();
// Draw targets
if (t.active) {
// Draw bullets
if (b.active) {
}
}
// Draw crosshair
drawCrosshair();
// Display score
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glRasterPos2f(10, 90);
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, c);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
glutSwapBuffers();
if (h == 0) h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
keyStates[key] = true;
exit(0);
keyStates[key] = false;
lookX /= length;
lookY /= length;
lookZ /= length;
glutWarpPointer(centerX, centerY);
fireBullet();
}
}
if (keyStates['w']) {
if (keyStates['s']) {
if (keyStates['a']) {
// Strafe left
if (keyStates['d']) {
// Strafe right
cameraY += moveSpeed;
if (keyStates['c']) {
cameraY -= moveSpeed;
}
// Keep camera above ground
updateBullets();
glutPostRedisplay();
glutInit(&argc, argv);
glutInitWindowSize(800, 600);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutKeyboardUpFunc(keyboardUp);
glutPassiveMotionFunc(mouse);
glutMouseFunc(mouseClick);
glutSetCursor(GLUT_CURSOR_NONE);
glutWarpPointer(400, 300);
initTargets();
// Enable depth testing
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;