【问题标题】:How does window.clear() works in SFML when making a character move in the screen?当角色在屏幕中移动时,window.clear() 如何在 SFML 中工作?
【发布时间】:2018-01-28 21:43:17
【问题描述】:

嗯,我一直在看有关如何使用 SFML 的教程。我目前正在学习在屏幕中移动精灵。添加之前 window.clear();每次我移动精灵时,它都会像一条轨迹一样离开,就像精灵是刷子一样。然后教程人说要在 window.draw(player); 之前添加 window.clear

你能解释一下这背后的逻辑吗?就像,窗口被清除,然后绘制角色并显示它。代码如下:

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

int main() {
    sf::RenderWindow window(sf::VideoMode(1920, 1080), "Screen", sf::Style::Default);
    sf::RectangleShape player(sf::Vector2f(100.0f, 100.0f));
    player.setFillColor(sf::Color::Green);

    //run as long as the window is open
    while (window.isOpen()) {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event evnt;
        while (window.pollEvent(evnt)) {
            switch (evnt.type) {
            case sf::Event::Closed:
                window.close();
                break;
            case sf::Event::Resized:
                printf("New window width: %i New window height: %i\n", evnt.size.width, evnt.size.height);
                break;
            case sf::Event::TextEntered:
                if (evnt.text.unicode < 128) {
                    printf("%c", evnt.text.unicode);
                }
            }
            // "close requested" event: we close the window
            if (evnt.type == sf::Event::Closed)
                window.close();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W)){
            player.move(0.0f, -0.1f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            player.move(-0.1f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S)) {
            player.move(0.0f, 0.1f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            player.move(0.1f, 0.0f);
        }
        window.clear();
        window.draw(player);
        window.display();
    }
    return 0;
}

【问题讨论】:

    标签: c++ logic sfml


    【解决方案1】:

    sf::RenderWindow::clear() 背后的逻辑其实很简单。您看到精灵后面没有清晰的轨迹的原因是因为您重新绘制了精灵而没有摆脱旧的。清除屏幕会删除屏幕上已经存在的任何内容,因此您最终会得到一个空白画布,以便在其更新的位置重新绘制所有内容。角色,也就是你的精灵,实际上并没有移动,它不断地在窗口的新位置重新绘制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-05
      • 2022-01-23
      • 2016-03-01
      • 1970-01-01
      • 2017-06-06
      • 2013-11-16
      • 2012-12-19
      • 2020-05-05
      相关资源
      最近更新 更多