SFML(1) | 自由落体小球
文章目录
- SFML(1) | 自由落体小球
 - 1. 目的
 - 2. SFML 适合做图形显示的理由
 - 3. 使用 SFML - 构建阶段
 - 4. 使用 SFML - C++ 代码
 - 5. 运行效果
 - 6. 总结
 - 7. References
 
1. 目的
通过一些简单的例子(2D小游戏的基础代码片段), 来学习 SFML 的使用。
2. SFML 适合做图形显示的理由
使用 SFML 做图形显示的库。 相比于其他用的过库:
- EasyX: 不开源, 不能跨平台使用, API 风格陈旧, 不是 C++ API
 - OpenCV 的 highgui 模块: highgui 不是 OpenCV 的最强项, 功能有限
 - SDL2: 完全用 C 写的, 不利于让我保持 C++ 语法的熟悉度
 - Qt: 有 GPL License 导致的潜在法律问题, 弃用
 - Dear imgui: 比较 geek, 默认的字体风格我受不了, “代码即文档” 也难度较大
 - SFML: 开源, 跨平台, 现代的 C++, License 友好, 文档直白, 功能齐全
 
3. 使用 SFML - 构建阶段
目前是 2024 年 2 月 9 日, 使用最新版 SFML 2.6.1。 我是 mac-mini 环境:
brew intall sfml
 
在 CMakeLists.txt 里, 为可执行程序链接 sfml 的库, 需要指明每一个 component:
cmake_minimum_required(VERSION 3.20)
project(free-falling-ball)
set(CMAKE_CXX_STANDARD 11)
add_executable(free-falling-ball
  main.cpp
)
find_package(SFML COMPONENTS graphics window system)
target_link_libraries(free-falling-ball PRIVATE sfml-graphics sfml-window sfml-system)
 
4. 使用 SFML - C++ 代码
#include <SFML/Graphics.hpp>
int main()
{
    constexpr int win_height = 600;
    constexpr int win_width = 600;
    constexpr int ball_radius = 20;
    const std::string title = "Free falling ball";
    sf::RenderWindow window(sf::VideoMode(win_width, win_height), title);
    float y = 100;
    float vy = 0;
    float g = 0.5;
    
    // run the program 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 event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
                window.close();
        }
        // clear the window with black color
        window.clear(sf::Color::Black);
        vy = vy + g;
        y = y + vy;
        if (y >= win_height - ball_radius)
        {
            vy = -0.95 * vy;
        }
        if (y > win_height - ball_radius)
        {
            y = win_height - ball_radius;
        }
        
        sf::CircleShape circle(ball_radius);
        circle.setFillColor(sf::Color::White);
        circle.setPosition(win_height / 2 - ball_radius, y);
        window.draw(circle);
        window.display();
        sf::sleep(sf::milliseconds(10));
    }
    return 0;
}
 
5. 运行效果

6. 总结
把 SFML 窗口显示, 和自由落体小球的动态效果相结合, 替代了原来使用的 EasyX, 特点:
- 依赖库是开源的, license 友好
 - 跨平台(windows,linux,macos)
 - modern C++, 而不是 C 或 legacy C++
 - 主流的 C++ 构建: 基于 CMake, 而不是直接创建 Makefile 或 VS Solution
 
7. References
- SFML Doc - Window
 - SFML Doc - graphics
 - 《C和C++游戏趣味编程》 Chapter2
 



















![[红日靶机渗透] ATKCK红队评估实战靶场三](https://img-blog.csdnimg.cn/direct/5ae67ddd302d4674bc36dedf3cd4819a.png)