0

I am trying to update the particles positions by calling a function for the class.. The values for v_x, v_y, a_x, a_y doesnt keep its new value after the function. I thought this would work because update_pos is a member function of the class. what am i doing wrong here?

class particle : public sf::CircleShape
{
    float mass;
    float v_x, v_y, a_x, a_y;


    public:
    particle(float radius,int x, int y)
    {
        setRadius(radius);
        setOrigin(radius, radius);
        setPosition(x, y);
        setFillColor(sf::Color::White);
        mass = radius;

        v_x = 0;
        v_y = 0;
        a_x = 0;
        a_y = 0;
    };

    void update_pos()
    {
        float g = 9;

        //upd acc
        a_x += g * 0 / mass;
        a_y += g / mass;
        
        //upd vel
        v_x += a_x;
        v_y += a_y;

        //move particle
        setPosition(getPosition().x + v_x, getPosition().y + v_y);
    }
};

this function is used in main to update every particle.

void update_particles(std::vector<particle>& particles)
{
    for (particle p : particles)
    {
        p.update_pos();
    }
}
1
  • Please extract a minimal reproducible example from your code. Usually, that allows you to get a better understanding of the problem and solve it themselves, but it's also required for this kind of question. Also, read How to Ask and take the tour. Commented Nov 24, 2022 at 7:30

1 Answer 1

8

This code

for (particle p : particles)

copies every particle in your vector, p is a copy. So you are changing copies of the particles in your vector, not the originals.

To avoid the copy you need a reference

for (particle& p : particles)

For a largish class like particle a reference is desirable anyway, just for efficiency reasons.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.