如何使用 C++ 在 SFML 中播放播放器

How ove the player in SFML with c++

我正在使用 SFML 使用 C++ 编写游戏。我已经编写了移动播放器的代码,但是当游戏开始播放器时,播放器会移动但是当我离开按钮时播放器 return 保持原来的状态 position.Can 你能帮帮我吗?

主要:

#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;

}

你所有的初始化代码都是运行 每一帧。这意味着在每一帧上,您都在创建(和销毁)一个新玩家,设置其纹理,并将其位置设置为 [0, 770].

将所有初始化移动到主绘图循环开始之前(while (window.isOpen()) 之前)。