首先,确保你已经安装了SFML库。如果没有安装,可以通过以下命令安装:

sudo apt-get install libsfml-dev

代码--

#include <SFML/Graphics.hpp> #include <vector> #include <cstdlib> #include <ctime> struct Meteor { sf::Vector2f position; sf::Vector2f velocity; sf::Color color; }; int main() { sf::RenderWindow window(sf::VideoMode(800, 600), "Meteor Shower"); std::vector<Meteor> meteors; srand(time(0)); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } // Add new meteor if (rand() % 10 == 0) { Meteor meteor; meteor.position = sf::Vector2f(rand() % 800, 0); meteor.velocity = sf::Vector2f(rand() % 5 - 2, rand() % 5 + 1); meteor.color = sf::Color(255, 255, 255, 255); meteors.push_back(meteor); } // Update meteor positions for (auto& meteor : meteors) { meteor.position += meteor.velocity; if (meteor.position.y > 600) { meteor.position.y = 0; meteor.position.x = rand() % 800; } } // Clear the window window.clear(sf::Color::Black); // Draw meteors for (const auto& meteor : meteors) { sf::RectangleShape rect(sf::Vector2f(2, 10)); rect.setPosition(meteor.position); rect.setFillColor(meteor.color); window.draw(rect); } // Display the window window.display(); } return 0; }

  1. Meteor结构体:定义了流星的基本属性,包括位置、速度和颜色。

  2. 主循环:在主循环中,程序不断更新流星的位置,并绘制到窗口中。

  3. 添加新流星:每隔一段时间(通过随机数控制),程序会添加一个新的流星到屏幕上。

  4. 更新流星位置:每个流星根据其速度更新位置,如果流星超出屏幕底部,则将其重置到顶部。

  5. 绘制流星:使用sf::RectangleShape绘制流星,并设置其位置和颜色。

运行效果

运行该程序后,你将看到一个简单的流星雨效果,流星从屏幕顶部随机位置出现,并以不同的速度向下滑动。

进一步优化

你可以通过以下方式进一步优化和扩展这个特效:

  • 增加流星的多样性:例如,不同颜色、不同形状的流星。

  • 增加背景效果:例如,星空背景或动态背景。

  • 增加交互性:例如,通过键盘或鼠标控制流星的生成和速度。

如有漏洞,欢迎评论哈!

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐