Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <iostream>
- class Game
- {
- public:
- Game();
- void run();
- private:
- void proccessEvent();
- void update(sf::Time deltaTime);
- void render();
- void handlePlayerInput(sf::Keyboard::Key key, bool isPressed);
- private:
- const float playerSpeed = 0.1f;
- const sf::Time TimePerFrame = sf::seconds(1.0f/60.0f);
- sf::RenderWindow mWindow;
- sf::Keyboard::Key key;
- sf::Texture texture;
- sf::RectangleShape rect;
- bool isPressed;
- bool mIsMovingUp;
- bool mIsMovingDown;
- bool mIsMovingRight;
- bool mIsMovingLeft;
- };
- Game::Game()
- : mWindow(sf::VideoMode(640, 480), "SFML Application"), rect()
- {
- // rect.setTexture(texture);
- rect.setFillColor(sf::Color::Red);
- rect.setSize(sf::Vector2f(20.0f,20.0f));
- }
- void Game::run()
- {
- sf::Clock clock;
- sf::Time timeSinceLastUpdate = sf::Time::Zero;
- while(mWindow.isOpen())
- {
- proccessEvent();
- sf::Time elapsedTime = clock.restart();
- timeSinceLastUpdate += elapsedTime;
- while(timeSinceLastUpdate > TimePerFrame)
- {
- timeSinceLastUpdate -= TimePerFrame;
- proccessEvent();
- update(TimePerFrame);
- }
- render();
- }
- }
- void Game::proccessEvent()
- {
- sf::Event event;
- while (mWindow.pollEvent(event)) {
- switch (event.type) {
- case sf::Event::Closed:
- mWindow.close();
- break;
- case sf::Event::KeyPressed:
- handlePlayerInput(event.key.code, true);
- break;
- case sf::Event::KeyReleased:
- handlePlayerInput(event.key.code, true);
- break;
- default:
- break;
- }
- }
- }
- void Game::update(sf::Time deltaTime)
- {
- sf::Vector2<float> movement(0.0f,0.0f);
- if(mIsMovingUp)
- {
- movement.y -= playerSpeed;
- }
- else if(mIsMovingDown)
- {
- movement.y += playerSpeed;
- }
- else if(mIsMovingRight)
- {
- movement.x -= playerSpeed;
- }
- else if(mIsMovingLeft)
- {
- movement.x += playerSpeed;
- }
- rect.move(movement * deltaTime.asSeconds());
- }
- void Game::render()
- {
- if(!texture.loadFromFile("/Users/tahajalili/Desktop/Eagle.png"))
- {
- std::cout << "Error occured" << std::endl;
- }
- mWindow.clear();
- mWindow.draw(rect);
- mWindow.display();
- }
- 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::D)
- {
- mIsMovingRight = isPressed;
- }
- else if (key == sf::Keyboard::A)
- {
- mIsMovingLeft = isPressed;
- }
- }
- int main(int, char const**)
- {
- Game game;
- game.run();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement