4
« on: March 27, 2020, 09:12:06 pm »
Started learning SFML. Got hands on this piece of code.
#include<SFML/Window.hpp>
#include<SFML/Graphics.hpp>
class Game{
public:
Game();
void run(); //to call in the main function
private:
void process_events(); //for user input
void update(); //actual code
void render(); //render after creating
void handle_player_input(sf::Keyboard::Key, bool);
private:
sf::RenderWindow m_window;
sf::CircleShape m_player;
bool is_moving_up;
bool is_moving_down;
bool is_moving_left;
bool is_moving_right;
};
Game::Game()
: m_window(sf::VideoMode(640, 480), "SFML App", sf::Style::Default)
, m_player(){
m_player.setRadius(40.f);
m_player.setPosition(100.f, 100.f);
m_player.setFillColor(sf::Color::Cyan);
}
void Game::run(){
while(m_window.isOpen()){
process_events();
update();
render();
}
}
void Game::handle_player_input(sf::Keyboard::Key key, bool is_pressed){
if(key == sf::Keyboard::W){
is_moving_up = is_pressed;
}
else if(key == sf::Keyboard::S){
is_moving_down = is_pressed;
}
else if(key == sf::Keyboard::A){
is_moving_left = is_pressed;
}
else if(key == sf::Keyboard::D){
is_moving_right = is_pressed;
}
}
void Game::process_events(){
sf::Event event;
while(m_window.pollEvent(event)){
sf::Event event;
switch(event.type){
case sf::Event::KeyPressed:
handle_player_input(event.key.code, true);
break;
case sf::Event::KeyReleased:
handle_player_input(event.key.code, false);
break;
case sf::Event::Closed:
m_window.close();
break;
}
}
}
void Game::update(){
sf::Vector2f movement(0.f, 0.f);
if(is_moving_up)
movement.y -= 1.f;
if(is_moving_down)
movement.x += 1.f;
if(is_moving_left)
movement.x -= 1.f;
if(is_moving_right)
movement.x += 1.f;
m_player.move(movement);
}
void Game::render(){
m_window.clear(sf::Color::Black);
m_window.draw(m_player);
m_window.display();
}
int main(){
Game game;
game.run();
}
I thought why bother about the boolean variable in handle_player_input() and changed the function to:
void Game::handle_player_input(){
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
m_player.move(0.f, 1.f);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
m_player.move(0.f, -1.f);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
m_player.move(-1.f, 0.f);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
m_player.move(1.f, 0.f);
}
But for both cases the shape is not moving though I am getting the cyan circle.
Edit1: I am using ArchLinux.(if that helps)
Edit2: changed {up, down, left, right} to {W, A, S. D} in first program(to match the second). Tested the program in a different linux distribution. Same result.
The event of closing the window also gets disabled when I run the program with the handle_user_input() function. I need to Ctrl+c to exit.