Search code examples
c++sfmlgame-maker

How ove the player in SFML with c++


I'm doing a game in c++ with SFML. I've written a code for move the player, but when the game start the player, moves but when i leave the button the player return at its original position.Can you help me, please?

The main:

#include <iostream>
#include <SFML/Graphics.hpp>

int main() {

    sf::RenderWindow window(sf::VideoMode(1320, 840), "Window");
    window.setPosition(sf::Vector2i(150, 50));
    window.setSize(sf::Vector2u(1320, 840));
    window.getPosition();
    window.setVerticalSyncEnabled(true);
    window.setFramerateLimit(5);
    window.getSize();

    while (window.isOpen()) {

        window.clear(sf::Color::White);

        //texture
        sf::Texture texture;
        if (!texture.loadFromFile("/users/gaetanodonnarumma/desktop/background1.png", sf::IntRect(0, 0, 1320, 840))) {
            return -1;
        }

        sf::Texture playerTexture;
        if (!playerTexture.loadFromFile("/users/gaetanodonnarumma/desktop/quadrato-giallo.jpg", sf::IntRect(0, 0, 70, 70))) {
            return -1;
        }

        //sprite
        sf::Sprite backgroud;
        backgroud.setTexture(texture);

        sf::Sprite player;
        double pX = 0;
        double pY = 770;
        player.setTexture(playerTexture);
        player.setPosition(sf::Vector2f(pX, pY));
        player.getPosition();

        sf::Event event;

        while (window.pollEvent(event)) {

            if (event.type == sf::Event::Closed) {
                window.close();
            }

            if (event.type == sf::Event::KeyPressed) {
                if (event.key.code == sf::Keyboard::D) {
                    player.move(10.f, 0.f);
                }
            }

            if (event.type == sf::Event::KeyPressed) {
                if (event.key.code == sf::Keyboard::D) {
                    player.setPosition(pX + 10, 770);
                }

            }

                if (event.type == sf::Event::KeyPressed) {
                    if (event.key.code == sf::Keyboard::A) {
                        player.move(-5.f, 0.f);
                    }
                }
        }

        //draw
        window.draw(backgroud);
        window.draw(player);

        window.display();

    }

    return 0;

}

Solution

  • All your initialization code is running on every frame. This means that on every frame, you are creating (and destroying) a new player, setting its texture, and setting its position to [0, 770].

    Move all the initialization to before the main draw loop begins (before while (window.isOpen())).