c++跳动粒子爱心源代码
时间: 2025-01-21 19:01:46 浏览: 58
以下是一个使用C++和SFML库实现的跳动粒子爱心源代码:
```cpp
#include <SFML/Graphics.hpp>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <ctime>
const float PI = 3.14159265358979323846f;
struct Particle {
sf::CircleShape shape;
sf::Vector2f velocity;
};
int main() {
srand(static_cast<unsigned>(time(0)));
sf::RenderWindow window(sf::VideoMode(800, 600), "跳动粒子爱心");
window.setFramerateLimit(60);
std::vector<Particle> particles;
particles.resize(1000);
for (auto& particle : particles) {
particle.shape.setRadius(2);
particle.shape.setFillColor(sf::Color::Red);
particle.shape.setPosition(
static_cast<float>(rand() % 800),
static_cast<float>(rand() % 600)
);
float angle = static_cast<float>(rand() % 360) * PI / 180.0f;
float speed = static_cast<float>(rand() % 3 + 1);
particle.velocity = sf::Vector2f(cos(angle) * speed, sin(angle) * speed);
}
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
for (auto& particle : particles) {
float x = particle.shape.getPosition().x;
float y = particle.shape.getPosition().y;
float dx = x - 400;
float dy = y - 300;
float distance = sqrt(dx * dx + dy * dy);
if (distance > 0) {
float force = 10000 / (distance * distance);
float angle = atan2(dy, dx);
particle.velocity.x -= force * cos(angle) / distance;
particle.velocity.y -= force * sin(angle) / distance;
}
particle.shape.move(particle.velocity);
if (particle.shape.getPosition().x < 0 || particle.shape.getPosition().x > 800)
particle.velocity.x = -particle.velocity.x;
if (particle.shape.getPosition().y < 0 || particle.shape.getPosition().y > 600)
particle.velocity.y = -particle.velocity.y;
}
window.clear();
for (const auto& particle : particles)
window.draw(particle.shape);
window.display();
}
return 0;
}
```
这段代码创建了一个800x600的窗口,并使用1000个红色粒子形成一个跳动的爱心效果。粒子受到中心点的吸引力,同时保持随机运动,模拟出跳动的效果。
阅读全文
相关推荐






