目录
Preface
在这本章中,我们将讨论:
- 在你的机器上 和 IDE 上安装SFML 环境
- 一个普通SFML应用程序的流程
- 打开和管理窗口
- 渲染的基本要素
Opening a window
正如您可能知道的,在屏幕上绘图需要一个窗口。幸运的是,SFML允许我们轻松打开和管理我们自己的窗口! 让我们像往常一样向我们的项目添加一个名为Main.cpp的文件。这将是应用程序的入口点。一个基本应用程序的基本框架如下:
#include <SFML/Graphics.hpp>
void main(int argc, char** argv[])
{
}
注意,我们已经包含了SFML graphics 的头文件。这将为我们提供打开窗口和绘制窗口所需的一切,因此,不再赘述,让我们看看打开窗口的代码:
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480),"First window!");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
// Close window button clicked.
window.close();
}
}
window.clear(sf::Color::Black);
// Draw here.
window.display();
}
system("pause");
return 0;
}
注意:SFML使用sf名称空间,因此我们必须在其数据类型、枚举和静态类成员前面加上“sf::”前缀。
我们在这里做的第一件事是声明并初始化RenderWindow类型的窗口实例。 在这种情况下,我们使用了它的构造函数,但是可以将它留空并稍后通过传入完全相同的参数来使用它的create方法,该方法只需要两个参数:sf::videoMode和 std::string 窗口标题。VodeMode的构造函数有两个参数: 窗口宽度和高度。还有第三个可选参数,以每像素位为单位设置颜色深度。它的默认值是32,这对于渲染我们的目的来说已经足够了,所以我们不需要为此担忧。
在创建窗口实例之后,我们输入一个while循环,该循环利用窗口方法之一来检查它是否仍然打开,即isOpen。这有效地创建了我们的游戏循环,这是我们所有代码的核心部分。
让我们来看看一个典型游戏的样子:
游戏循环的目的是检查事件和输入,更新帧之间的游戏世界,这意味着移动玩家,敌人,checking for changes,等等,最后在屏幕上绘制一切。这个过程需要每秒重复多次,直到窗口关闭。每个应用程序的时间长短不一样,有的甚至高达每秒数千次迭代。在第二章中, 我们将讨论管理和限制我们的应用程序的帧率,以及让游戏以恒定的速度运行。
大多数应用程序需要有一种方法来检查窗口是否已经关闭、调整大小或移动。这就是事件处理的作用。SFML提供了一个 event 类,我们可以使用它来存储事件信息。在我们游戏循环的每次迭代中,我们需要利用我们窗口对象的 pollEvent 方法来检查发生的事件,并对它们进行处理。这种情况下,我们只对鼠标点击关闭窗口按钮时发出的事件感兴趣。 我们可以检查类Event的公共成员类型是否与正确的枚举成员匹配,在这种情况下它是sf :: Event :: Closed。 如果是的话,我们可以调用window实例的close方法,我们的程序将终止。
注意: 事件必须在所有SFML应用程序中处理。如果没有事件循环轮询事件,窗口将变得无响应,因为它不仅向用户提供事件信息,而且还为窗口本身提供了一种处理其内部事件的方法,这是窗口对移动或调整大小作出反应的必要条件。<