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

标签 c++ sfml game-maker

我正在使用 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()) 之前)。

关于c++ - 如何使用 C++ 在 SFML 中播放播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35772056/

相关文章:

c++ - 使用新的 C++11 语法的 auto 函数声明,但有 auto& 而没有 ->

c++ - 在终止值 C++ 之前查找序列的最后一个值

c++ - SFML 在多线程中失败

game-maker - 游戏制作者 lengthdir 内部实现

android - 如何通过按 Android 设备上的后退按钮关闭 GameMaker 游戏?

C++:本地时间提升一小时

c++ - 如何在用户创建的库中打开 Windows 资源管理器?

c++ - 处理鼠标事件 SFML

c++ - 如何修复 "initial value of reference to non-const must be an lvalue?"

java - 数据包从 Game Maker 到 Node,js 不分离