Skip to content

Instantly share code, notes, and snippets.

@Przemekkkth
Created June 29, 2023 17:46
Show Gist options
  • Save Przemekkkth/93ff286092f5737bc8941e5176c1917d to your computer and use it in GitHub Desktop.
Save Przemekkkth/93ff286092f5737bc8941e5176c1917d to your computer and use it in GitHub Desktop.
A SFML application that draws a cardioid.
#include <SFML/Graphics.hpp>
#include <algorithm>
#include <cmath>
class Cardioid
{
public:
Cardioid()
: m_radius(400), m_num_lines(150), m_counter(0.0f), m_inc(0.01f), m_translate(sf::Vector2i(1000/2, 600/2)){}
void draw(sf::RenderWindow& w)
{
int time = m_clock.getElapsedTime().asMilliseconds();
m_radius = 250 + 50 * std::abs(std::sin(time * 0.004) - 0.5);
float factor = 1 + 0.0001 * time;
sf::Color color = getColor();
for(int i = 0; i < m_num_lines; ++i)
{
float theta = ( (2 * M_PI) / m_num_lines) * i;
int x1 = m_radius * std::cos(theta) + m_translate.x;
int y1 = m_radius * std::sin(theta) + m_translate.y;
int x2 = m_radius * std::cos(factor*theta) + m_translate.x;
int y2 = m_radius * std::sin(factor*theta) + m_translate.y;
sf::Vertex line[] =
{
sf::Vertex(sf::Vector2f(x1, y1), color),
sf::Vertex(sf::Vector2f(x2, y2), color)
};
w.draw(line, 2, sf::Lines);
}
}
sf::Color getColor(){
m_counter += m_inc;
if (!(0.009 < m_counter && m_counter < 1)) {
m_counter = std::max(std::min(m_counter, 1.0f), 0.0f);
m_inc = -m_inc;
}
sf::Color color1 = sf::Color::Red;
sf::Color color2 = sf::Color::Green;
int r = (color2.r - color1.r) * m_counter + color1.r;
int g = (color2.g - color1.g) * m_counter + color1.g;
int b = (color2.b - color1.b) * m_counter + color1.b;
return sf::Color(r, g, b);
}
private:
int m_radius;
int m_num_lines;
float m_counter;
float m_inc;
sf::Clock m_clock;
sf::Vector2i m_translate;
};
int main()
{
const unsigned int FPS = 60; //The desired FPS. (The number of updates each second).
sf::RenderWindow window(sf::VideoMode(1000, 600), "Cardioid SFML C++");
window.setFramerateLimit(FPS);
Cardioid cardioid;
sf::Event ev;
while (window.isOpen())
{
//Handle events
while (window.pollEvent(ev))
{
if (ev.type == sf::Event::Closed)
window.close();
}
// Draw stuff
window.clear();
cardioid.draw(window);
window.display();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment