【问题标题】:How ove the player in SFML with c++如何使用 c++ 了解 SFML 中的播放器
【发布时间】:2016-06-16 18:31:33
【问题描述】:

我正在用 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;

}

【问题讨论】:

  • 您的按键D 的一个按键事件移动播放器,另一个设置其绝对位置。为什么D 有 2 个其他相同的关键事件?

标签: c++ sfml game-maker


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-25
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2015-01-11
    相关资源
    最近更新 更多