I'm trying to make a Snake clone using C++ and OpenGL/GLUT. However, I've been having trouble programming the short time intervals allowed for input between movements. I've tried a few timing methods, and I ended up making a class for it (as you'll see below). This seems to be the best way to program the input delays (rather than glutTimerFunc() or sleep()), because the timer runs separately from the game loop, instead of putting the whole program on hold. This is important because I want the player to be able to pause at any time. Unfortunately, I'm having issues with this method now too. My timer class seems to ignore the double I give it for the time limit (simply represented as double "limit").
To test the class, I've set up a simple, looping console program that displays directional input from the user at the point when the timer reaches the time limit. It's supposed to display input every 0.33 seconds. Instead, it displays input at fixed intervals that seem to be around 0.8 seconds apart, regardless of what value has been given for the time limit. Why won't it display input at the given time intervals, and why has it made it's own time limit?
This also happens to be my first major C++/OpenGL project without a tutorial, so any comments or advice on my code/methods is appreciated!
#include <iostream>
#include "timer.h"
// Include all files necessary for OpenGL/GLUT here.
using namespace std;
Timer timer;
// Insert necessary OpenGL/GLUT code for display/looping here.
void update(int value)
{
if (timer.checkTime())
{
if (GetAsyncKeyState(VK_LEFT))
cout << "You pressed LEFT!" << endl;
else if (GetAsyncKeyState(VK_RIGHT))
cout << "You pressed RIGHT!" << endl;
else if (GetAsyncKeyState(VK_UP))
cout << "You pressed UP!" << endl;
else if (GetAsyncKeyState(VK_DOWN))
cout << "You pressed DOWN!" << endl;
}
glutTimerFunc(1000/60, update, 0);
glutPostRedisplay();
}
timer.h
#pragma once
#include <time.h>
class Timer
{
public:
Timer();
bool checkTime(double limit = 0.33);
private:
double getElapsed();
time_t start;
time_t now;
double elapsed;
bool running;
};
timer.cpp
#include "timer.h"
Timer::Timer()
{
running = false;
}
bool Timer::checkTime(double limit)
{
elapsed = getElapsed();
if (elapsed < limit)
{
return false;
}
else if (elapsed >= limit)
{
running = false;
return true;
}
}
double Timer::getElapsed()
{
if (! running)
{
time(&start);
running = true;
return 0.00;
}
else
{
time(&now);
return difftime(now, start);
}
}