Kevin Karlsson
Kevin Karlsson

Reputation: 13

class member values doesn't get changed by function... "noob question"

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();
    }
}

Upvotes: 0

Views: 39

Answers (1)

john
john

Reputation: 87959

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.

Upvotes: 8

Related Questions