Search code examples
c++sfml

(SFML, C++) How to access specific sf::Vertex in dynamically allocated sf::VertexArray?


I am new to SFML, learning it in C++ and I have this problem which I can't solve.
What my program (class) contains is:

in header file:

sf::VertexArray *hitbox;

in source file:

this->hitbox = new sf::VertexArray(sf::TriangleFan, 20); //example

and there's a method

void Object::setPosition(sf::Vector2f position)
{
    if(this->hitbox->getVertexCount()!=0)
    {
        this->hitbox->position = position; //error here
    }
}

Compiler says this:

 error: 'class sf::VertexArray' has no member named 'position'
   this->hitbox->position = position;
                 ^

So the problem is that I want to change the position of the first vertex, but it seems that I can't access it when I alloc sf::VertexArray dynamically. I've read on https://www.sfml-dev.org/ that sf::VertexArray is in fact std::vector<sf::Vertex> with [] operator overload, so there should be a way to do this, but I struggle to find it. Additionally, the class does not inherit from sf::Transformable. How can I solve this issue?

Edit:
this->hitbox[0]->position = position;
or
this->hitbox[0].position = position;
don't solve this issue. In first case compiler has problem with hitbox[0] not being a pointer, in second case it's the same error as stated above/


Solution

  • Since this->hitbox is a pointer to a sf::VertexArray, you need to dereference it before using the operator[]:

    (*(this->hitbox))[0].position = position;
    

    It would probably be better to not use a pointer here at all.