如何使用 c++ 在 SFML 中配置播放器

How ove the player in SFML with c++

本文关键字:配置 播放器 SFML 何使用 c++      更新时间:2023-10-16

我正在用SFML用c++做一个游戏。我已经编写了一个移动玩家的代码,但是当游戏开始时,玩家会移动,但是当我离开按钮时,玩家会返回其原始位置。你能帮帮我吗?

主要:

#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()) 之前)。