Hello
I was trying out the code given in The SFML Game Dev book in the first chapter:
Here are main.cpp, Game.h and Game.cpp
Game.h#ifndef GAME_H
#define GAME_H
#include <SFML/Graphics.hpp>
class Game : private sf::NonCopyable
{
public:
Game();
void run();
~Game();
private:
void processEvents();
void update();
void handlePlayerInput(sf::Keyboard::Key key, bool isPressed);
void render();
private:
sf::RenderWindow mWindow;
sf::CircleShape mPlayer;
bool mIsMovingUp;
bool mIsMovingDown;
bool mIsMovingLeft;
bool mIsMovingRight;
};
#endif // GAME_H
Game.cpp#include "Game.h"
Game::Game() : mWindow(sf::VideoMode(640, 480), "SFML Application")
{
mPlayer.setRadius(40.0f);
mPlayer.setPosition(100.f, 100.f);
mPlayer.setFillColor(sf::Color::Cyan);
}
void Game::run()
{
while(mWindow.isOpen())
{
processEvents();
update();
render();
}
}
void Game::processEvents()
{
sf::Event event;
while(mWindow.pollEvent((event)))
{
switch(event.type)
{
case sf::Event::KeyPressed:
handlePlayerInput(event.key.code, true);
break;
case sf::Event::KeyReleased:
handlePlayerInput(event.key.code, false);
break;
case sf::Event::Closed:
mWindow.close();
break;
}
}
}
void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed)
{
if(key == sf::Keyboard::W)
mIsMovingUp = isPressed;
else if(key == sf::Keyboard::S)
mIsMovingDown = isPressed;
else if(key == sf::Keyboard::A)
mIsMovingLeft = isPressed;
else if(key == sf::Keyboard::D)
mIsMovingRight = isPressed;
}
void Game::update()
{
sf::Vector2f movement(0.f, 0.f);
if(mIsMovingUp)
movement.y -= 1.f;
if(mIsMovingDown)
movement.y += 1.f;
if(mIsMovingLeft)
movement.x -= 1.f;
if(mIsMovingRight)
movement.x += 1.f;
mPlayer.move(movement);
}
void Game::render()
{
mWindow.clear();
mWindow.draw(mPlayer);
mWindow.display();
}
Game::~Game()
{
//dtor
main.cpp#include "Game.h"
int main()
{
Game game;
game.run();
}
But whenever I am running my code, the circle starts moving upwards automatically and if I press the W key it stops moving and then everything works normal and as expected.
If I change Game.cpp as follows, everything is normal:
.
.
.
Game::Game() : mWindow(sf::VideoMode(640, 480), "SFML Application"), mIsMovingUp(false)
{
.
.
.
So what's exactly the problem in the code in the first case and why is the variable
mIsMovingUp only initialized during runtime?
Thanks