Created
December 24, 2017 08:43
-
-
Save MarioLiebisch/2e86796613c6aec226eda5717371d7f6 to your computer and use it in GitHub Desktop.
A simple example on how one could render concave shapes such as tetrominos using SFML's `sf::VertexArray`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SFML/Graphics.hpp> | |
int main() { | |
sf::RenderWindow window(sf::VideoMode(800, 600), "Tetrominos"); | |
// The quads approach is easiest to understand | |
// (Note this is not supported on mobile targets and you'd have to define triangles instead) | |
sf::VertexArray quads(sf::Quads); | |
// Left piece | |
quads.append({{0, 0}, sf::Color::White}); | |
quads.append({{95, 0}, sf::Color::Red}); | |
quads.append({{95, 95}, sf::Color::Green}); | |
quads.append({{0, 95}, sf::Color::Blue}); | |
// Center piece | |
quads.append({{100, 0}, sf::Color::White}); | |
quads.append({{195, 0}, sf::Color::Red}); | |
quads.append({{195, 95}, sf::Color::Green}); | |
quads.append({{100, 95}, sf::Color::Blue}); | |
// Right piece | |
quads.append({{200, 0}, sf::Color::White}); | |
quads.append({{295, 0}, sf::Color::Red}); | |
quads.append({{295, 95}, sf::Color::Green}); | |
quads.append({{200, 95}, sf::Color::Blue}); | |
// Bottom piece | |
quads.append({{100, 100}, sf::Color::White}); | |
quads.append({{195, 100}, sf::Color::Red}); | |
quads.append({{195, 195}, sf::Color::Green}); | |
quads.append({{100, 195}, sf::Color::Blue}); | |
// Triangle fan makes it shorter, but a bit more complex to understandd | |
sf::VertexArray triangleFan(sf::TriangleFan); | |
// Starting point is the bottom left corner of the center piece | |
triangleFan.append({{100, 100}, sf::Color::White}); | |
triangleFan.append({{0, 100}, sf::Color::Red}); | |
triangleFan.append({{0, 0}, sf::Color::Green}); | |
triangleFan.append({{300, 0}, sf::Color::Blue}); | |
triangleFan.append({{300, 100}, sf::Color::Magenta}); | |
// The next point creates an invisible triangle just to move to the center piece | |
triangleFan.append({{200, 100}, sf::Color::Black}); | |
triangleFan.append({{200, 200}, sf::Color::Cyan}); | |
triangleFan.append({{100, 200}, sf::Color::Yellow}); | |
while (window.isOpen()) { | |
sf::Event event; | |
while (window.pollEvent(event)) { | |
if (event.type == sf::Event::Closed) | |
window.close(); | |
} | |
window.clear(); | |
sf::Transform transform; | |
transform.translate({50, 50}); | |
window.draw(quads, transform); | |
transform.translate({0, 300}); | |
window.draw(triangleFan, transform); | |
window.display(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment