嗯,我一直在看一个关于如何使用SFML的教程。我现在正在学习如何在屏幕上移动精灵。在添加window.clear()之前,每次我移动精灵时,它都会留下一条轨迹,就像精灵是画笔一样。然后,指导人员说要在window.draw(播放器)之前添加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;
}
发布于 2018-01-29 05:46:31
sf::RenderWindow::clear()
背后的逻辑实际上非常简单。在没有清除的情况下看到精灵后面有一条轨迹的原因是,您重新绘制了精灵,而没有删除旧的精灵。清除屏幕将清除屏幕上已有的所有内容,因此您最终会得到一个空白画布,以便在更新后的位置重新绘制所有内容。这个角色,就是你的精灵,实际上并不是在移动,而是不断地在窗口的新位置被重新绘制。
https://stackoverflow.com/questions/48491646
复制相似问题