Try to make animation less dependant on framerate

This commit is contained in:
Corentin Jabot 2021-06-22 15:37:36 +02:00 committed by Patricia Aas
parent a69e66d114
commit ecf2ab8b6c
4 changed files with 29 additions and 24 deletions

View File

@ -9,6 +9,7 @@
Canvas::Canvas()
: window(sf::VideoMode(windowDimensions().width, windowDimensions().height), "Pacman", sf::Style::Titlebar | sf::Style::Close) {
window.setFramerateLimit(60);
window.setVerticalSyncEnabled(true);
maze_texture = loadTexture("maze.png");

View File

@ -12,17 +12,31 @@ auto Game::now() {
}
void Game::run() {
InputState inputState;
auto current_time = now();
while (!inputState.close) {
processEvents(inputState);
auto time_delta = now() - current_time;
auto milli_delta = std::chrono::duration_cast<std::chrono::milliseconds>(time_delta);
pacMan.update(milli_delta, inputState, board);
eatPellets();
current_time += time_delta;
canvas.update(pacMan, pellets, superPellets);
}
const std::chrono::milliseconds delta_time (1000/60);
std::chrono::milliseconds t(0);
std::chrono::milliseconds accumulator(0);
auto current_time = now();
InputState inputState;
while (true) {
auto newTime = now();
auto frameTime = std::chrono::duration_cast<std::chrono::milliseconds>(newTime - current_time);
current_time = newTime;
accumulator += frameTime;
processEvents(inputState);
if(inputState.close)
return;
while ( accumulator >= delta_time ) {
pacMan.update(delta_time, inputState, board);
eatPellets();
accumulator -= delta_time;
t += delta_time;
}
canvas.update(pacMan, pellets, superPellets);
}
}
void Game::eatPellets() {

View File

@ -13,17 +13,7 @@ Position PacMan::position() const {
}
Position PacMan::positionInGrid() const {
switch (direction) {
case Direction::LEFT:
case Direction::RIGHT:
return { std::floor(pos.x), std::round(pos.y) };
case Direction::UP:
case Direction::DOWN:
return { std::floor(pos.x), std::round(pos.y) };
default:
return pos;
}
return pos;
return { std::round(pos.x), std::round(pos.y) };
}
void PacMan::update(std::chrono::milliseconds time_delta, InputState state, const Board & board) {
@ -50,7 +40,7 @@ void PacMan::updateAnimationPosition(std::chrono::milliseconds time_delta) {
}
void PacMan::updateMazePosition(std::chrono::milliseconds time_delta, const Board & board) {
float position_delta = time_delta.count() / 150.0;
float position_delta = 0.004 * time_delta.count();
// Handle teleport
if (pos.x >= COLUMNS - 1 && direction == Direction::RIGHT) {

View File

@ -17,7 +17,7 @@ PositionInt PacManAnimation::animationFrame(Direction direction) const {
}
void PacManAnimation::updateAnimationPosition(std::chrono::milliseconds time_delta) {
animation_position_delta += (time_delta.count() / 100.0);
animation_position_delta += (0.02) * float(time_delta.count());
animation_position = int(animation_position + animation_position_delta) % 4;
animation_position_delta = (animation_position_delta < 1) ? animation_position_delta : (animation_position_delta - 1);
}