Hi
i wrote the code same as the book but the after the key is released the bool variables won't reset to false
and object moves without stopping
also the object moves opposite direction, when i press W set the mPlayer.move(0,-1) but it moves to down
Main.cpp#ifdef SFML_STATIC
#pragma comment(lib, "glew.lib")
#pragma comment(lib, "freetype.lib")
#pragma comment(lib, "jpeg.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "gdi32.lib")
#endif // SFML_STATIC
#include "game.h"
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
Game game;
game.run();
return 0;
}
game.h#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#ifndef GAME_H
#define GAME_H
class Game{
private:
void processEvents();
void update();
void render();
private:
sf::RenderWindow mWindow;
sf::CircleShape mPlayer;
bool mIsMovingUp, mIsMovingDown, mIsMovingLeft, mIsMovingRight;
public:
Game();
void HandlePlayerInput(sf::Keyboard::Key, bool);
void run();
};
#endif // GAME_H
game.cpp#include "game.h"
Game::Game() : mWindow(sf::VideoMode(640, 480), "SFML Application"), mPlayer(){
mPlayer.setRadius(40.f);
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();
}