Hi, I'm building a SFML and c++ Galaga clone. I'm trying to move the ship in a continuous way, but I can't understand why mi ship still moving like "pixel by pixel". I've readed that use deltatime to do this is a good practice. This is the code that I used for it:
Game::Run(), where I calculate my deltatime:
void Game::Run() {
float newTime, frameTime, interpolation;
float currentTime = this->m_clock.getElapsedTime().asSeconds();
float accumulator = 0.0f;
while (this->m_data->m_window.isOpen()) {
this->m_data->m_machine.ProcessStateChanges();
newTime = this->m_clock.getElapsedTime().asSeconds();
frameTime = newTime - currentTime;
if (frameTime > 0.25f) {
frameTime = 0.25f;
}
currentTime = newTime;
accumulator += frameTime;
while (accumulator >= m_dt) {
this->m_data->m_machine.GetActiveState()->HandleInput();
this->m_data->m_machine.GetActiveState()->Update(m_dt);
accumulator -= m_dt;
}
interpolation = accumulator / m_dt;
this->m_data->m_machine.GetActiveState()->Draw(interpolation);
}
}
void Batalla::HandleInput () ("Batalla" is a state of the game)
void Batalla::HandleInput() {
sf::Event event;
while (this->m_data->m_window.pollEvent(event)) {
if (sf::Event::Closed == event.type || sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) {
this->m_data->m_window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
m_PlayerIsMoving = true;
m_playerDirection = -1;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
m_isFiring = true;
}
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
m_PlayerIsMoving = true;
m_playerDirection = 1;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
m_isFiring = true;
}
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
m_isFiring = true;
}
}
}
void Batalla:Update(float dt)
void Batalla::Update(float dt) {
if (m_PlayerIsMoving) {
m_player->Move(dt, m_playerDirection);
m_playerDirection = 0;
m_PlayerIsMoving = false;
}
if (m_isFiring) {
Bullet * l_newBullet = new Bullet(m_data, sf::Vector2f(m_player->GetSprite().getPosition().x, m_player->GetSprite().getPosition().y));
m_bulletVector.push_back(l_newBullet);
m_isFiring = false;
}
for (int i = 0; i < m_bulletVector.size(); i++) {
m_bulletVector.at(i)->Move(dt);
}
}
void Batalla::Draw(float dt)
void Batalla::Draw(float dt) {
this->m_data->m_window.clear(sf::Color::Black);
this->m_data->m_window.draw(this->m_background);
m_player->Draw();
for (int i = 0; i < m_bulletVector.size(); i++) {
m_bulletVector.at(i)->Draw();
}
this->m_data->m_window.display();
}
void Player::Move(float l_dt, int l_playerDirection) (moves the player's ship)
void Player::Move(float l_dt, int l_playerDirection) {
m_playerSprite.move((SHIP_SPEED * l_dt * l_playerDirection), 0);
}
Can anyone help please help me? Thank you.