Bien sûr, voici une autre série de 10 exemples de codes SFML en C++ :
- Créer des particules en mouvement :
#include <SFML/Graphics.hpp>
#include <random>
struct Particle
{
sf::Vector2f position;
sf::Vector2f velocity;
sf::Color color;
float lifespan;
};
std::default_random_engine generator;
std::uniform_real_distribution<float> position_distribution(0.0f, 800.0f);
std::normal_distribution<float> speed_distribution(50.0f, 10.0f);
std::uniform_real_distribution<float> lifespan_distribution(1.0f, 2.0f);
Particle createParticle()
{
Particle particle;
particle.position = sf::Vector2f(position_distribution(generator), position_distribution(generator));
particle.velocity = sf::Vector2f(speed_distribution(generator), speed_distribution(generator));
particle.color = sf::Color::Red;
particle.lifespan = lifespan_distribution(generator);
return particle;
}
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
std::vector<Particle> particles;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
particles.push_back(createParticle());
for (auto& particle : particles)
{
particle.position += particle.velocity * 0.01f;
particle.lifespan -= 0.01f;
}
particles.erase(std::remove_if(particles.begin(), particles.end(), [](const Particle& p){ return p.lifespan <= 0.0f; }), particles.end());
window.clear();
for (const auto& particle : particles)
{
sf::CircleShape shape(5.0f);
shape.setPosition(particle.position);
shape.setFillColor(particle.color);
window.draw(shape);
}
window.display();
}
return 0;
}
- Afficher une animation en boucle :
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
sf::Texture texture1;
texture1.loadFromFile("frame1.png");
sf::Texture texture2;
texture2.loadFromFile("frame2.png");
sf::Texture texture3;
texture3.loadFromFile("frame3.png");
sf::Sprite sprite(texture1);
sf::Clock clock;
float frame_time = 0.2f;
bool frame1 = true;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
if (clock.getElapsedTime().asSeconds() > frame_time)
{
if (frame1)
{
sprite.setTexture(texture2);
frame1 = false;
}
else
{
sprite.setTexture(texture3);
frame1 = true;
}
clock.restart();
}
window.clear();
window.draw(sprite);
window.display();
}
return 0;
}
- Afficher une carte avec des tuiles :
#include <SFML/Graphics.hpp>
#include <iostream>
#include <fstream>
#include <string>
const int MAP_WIDTH = 16;
const int MAP_HEIGHT = 9;
const int TILE_SIZE = 64;
int map[MAP_HEIGHT][MAP_WIDTH] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1,