Skip to content

Commit

Permalink
fixed delta time
Browse files Browse the repository at this point in the history
  • Loading branch information
OhhhZenix committed Feb 9, 2025
1 parent 08f1ab2 commit d818218
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 19 deletions.
18 changes: 4 additions & 14 deletions src/Core/Game.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,6 @@ Game::~Game() {
SDL_Quit();
}

f64 Game::getDeltaTime() {
static u64 currentTime = 0;
static u64 lastTime = 0;

lastTime = currentTime;
currentTime = SDL_GetPerformanceCounter();

return ((currentTime - lastTime) * 1000 / (double)SDL_GetPerformanceFrequency());
}

f64 Game::getDeltaTimeInSeconds() {
return this->getDeltaTime() / 1000;
}

void Game::run() {
SDL_Event event = { 0 };
while (isRunning) {
Expand All @@ -55,5 +41,9 @@ void Game::run() {
SDL_RenderClear(this->renderer);
this->player->render(this);
SDL_RenderPresent(this->renderer);

this->lastTime = this->currentTime;
this->currentTime = SDL_GetPerformanceCounter();
this->deltaTime = (this->currentTime - this->lastTime) / (f64)SDL_GetPerformanceFrequency();
}
}
5 changes: 3 additions & 2 deletions src/Core/Game.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ struct Game {
SDL_Renderer* renderer = nullptr;
bool isRunning = true;
std::unordered_map<u32, bool> isKeyDown = {};
u64 lastTime = 0;
u64 currentTime = 0;
f64 deltaTime = 0;
Player* player = nullptr;

Game();
~Game();
f64 getDeltaTime();
f64 getDeltaTimeInSeconds();
void run();
};
10 changes: 7 additions & 3 deletions src/Entity/Player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#include "Core/Game.hpp"
#include "Core/Types.hpp"
#include "glm/fwd.hpp"
#include <iostream>

Player::Player(glm::vec2 startingPosition) {
this->position = startingPosition;
Expand All @@ -11,8 +13,10 @@ Player::~Player() {}

void Player::update(Game* game) {
glm::vec2 direction = { 0, 0 };
f32 speed = 1;
f32 dt = game->getDeltaTimeInSeconds();
f32 distance = 1000;
f32 time = game->deltaTime;

std::cout << time << std::endl;

if (game->isKeyDown[SDLK_UP]) {
direction.y -= 1;
Expand All @@ -31,7 +35,7 @@ void Player::update(Game* game) {
}

if (glm::length(direction) > 0) {
this->position += glm::normalize(direction * speed * dt);
this->position += glm::normalize(direction) * distance * time;
}
}

Expand Down

0 comments on commit d818218

Please sign in to comment.