SFML community forums

Help => Graphics => Topic started by: Moonglum on March 17, 2023, 10:02:30 am

Title: Changing vertices
Post by: Moonglum on March 17, 2023, 10:02:30 am
I am trying to draw a line in SFML. I use the ...

sf::Vertex line[]=
        {
            sf::Vertex(sf::Vector2f(sx,sy)),
            sf::Vertex(sf::Vector2f(ex,ey))
        };


... command, where sx,sy,ex,ey are previously defined as 'float' and given appropriate values. However, I understand that this defines a new variable called 'line' with two vertices. Great but I now want to draw the line in a new position. How do change the position of the line? If I just run that command again then it tells me that 'line' is already used. This is no good for a game where line drawing is in a loop.

Please can someone tell me how to change the line position.

Many thanks

Moon.
Title: Re: Changing vertices
Post by: joe5513 on March 17, 2023, 12:39:22 pm
You can create function that takes two vectors as parameters which are start and end of the line.
Then simply pass sf::Vertex array with vertices constructed from provided start and end positions to window's draw method

void draw_line(const sf::Vector2f& a, const sf::Vector2f&b)
{
    sf::Vertex line[]=
        {
            sf::Vertex(a),
            sf::Vertex(b)
        };

    window.draw(line ... )
}

-----

draw_line(sf::Vector2f(0, 0), sf::Vector2f(10, 10));
 
Title: Re: Changing vertices
Post by: Stauricus on March 17, 2023, 03:01:21 pm
'line' is an array, so you access its elements by using its indexes. line[0] and line[1], in this case.
inside each element, you made a sf::Vertex (https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Vertex.php). you can access its 'position' and then its 'x' and 'y' values.
so, to change them, you should use something like this:
line[0].position.x = 100;
or, if you want to change the vertex position in one line:
line[0].position = sf::Vector2f(100, 100);

You can create function that takes two vectors as parameters which are start and end of the line.
Then simply pass sf::Vertex array with vertices constructed from provided start and end positions to window's draw method

void draw_line(const sf::Vector2f& a, const sf::Vector2f&b)
{
    sf::Vertex line[]=
        {
            sf::Vertex(a),
            sf::Vertex(b)
        };

    window.draw(line ... )
}
draw_line(sf::Vector2f(0, 0), sf::Vector2f(10, 10));
 

the problem in this case is that you would be creating the line every iteration. may not be much for lines, but for most cases you create shapes and/or sprites just once and then, each iteration, just draw them.
and also the function is missing a reference to the window  ;D
Title: Re: Changing vertices
Post by: Moonglum on March 18, 2023, 01:32:32 pm
Awesome. Thanks Stauricus. That works a treat. Your points are noted. Just learning at the moment. This is fab info. Thank you.

Moon.