How do I draw a primitive of my choice from a constructed VertexArray? In the example below I am adding two vertices to the 'vertices' array and I am trying to draw it with 'window.draw(vertices, 2, sf::Lines)' but it gives me an error. I know I can just create line object with 'sf::Vertex foo[] = {..}' but I want to be able to keep appending vertices to the array instead of initializing all at once.
#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
// Create the main window
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML");
sf::Clock clock;
sf::VertexArray vertices;
sf::Vertex vertex;
vertex.position = sf::Vector2f(0, 0);
vertex.color = sf::Color(100, 0, 200);
vertices.append(vertex);
vertex.position = sf::Vector2f(100, 100);
vertex.color = sf::Color(100, 0, 200);
vertices.append(vertex);
// Start the game loop
bool running = true;
while (running)
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed)
running = false;
}
window.clear(sf::Color::Black);
window.draw(vertices,2 ,sf::Lines);
window.display();
}
return 0;
}
You can call vertices.setPrimitiveType(sf::Lines);
after declaring sf::VertexArray vertices;
, then draw it: window.draw(vertices);
Or you can set its primitive type in the constructor, along with number of points, then you can access those points with operator[]
:
sf::VertexArray line(sf::Lines, 2); //or sf::LineStrip
line[0].position = sf::Vector2f(0, 0);
line[0].color = sf::Color(100, 0, 200);
line[1].position = sf::Vector2f(100, 100);
line[1].color = sf::Color(100, 0, 200);
...
window.draw(line);
Reference: enum sf::PrimitiveType, sf::VertexArray, VertexArray tutorial