Particle system: All particles move in the same direction

Viewed 125

I'm trying to create a particle system. In the ParticleSystem constructor I create new particles with a random color and velocity. When I run my code, all particles have different colors but move in the same direction

#include "stdafx.h"
#include "ParticleSystem.h"

ParticleSystem::ParticleSystem(){}
ParticleSystem::ParticleSystem(float size, int sides, sf::Vector2f velocity, 
int pAtm)
: Particle(size, sides, velocity, pAtm)
{


    for (int it = 0; it < pAtm; it++) {
        particleVector.push_back(Particle(size, sides, velocity, pAtm));
    }
}

 ParticleSystem::~ParticleSystem()
 {
 }

 const bool& ParticleSystem::getClick() const
 {
  return isClick;
 }

  void ParticleSystem::checkForClick()
  {
   if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
    isClick = true;
    }
    else {
    isClick = false;
    }
   }

 void ParticleSystem::update(const float& ft)
  {
  checkForClick();
  move(dt);
  //update1(dt);
  }

 void ParticleSystem::render(sf::RenderTarget& target)
 {
for (std::vector<Particle>::iterator it = particleVector.begin(); it != particleVector.end(); ++it) {
        target.draw(shape);

  }

 }
1 Answers
for (int it = 0; it < pAtm; it++) {
        particleVector.push_back(Particle(size, sides, velocity, pAtm));
}

You're giving all your particles the same velocity vector. If you want a random velocity for each particle, you need to generate a new random velocity for each particle :

for (int it = 0; it < pAtm; it++) {
        sf::Vector2f randomVelocity = generateRandomVelocity(); // Put the random vector generation logic in a function
        particleVector.push_back(Particle(size, sides, randomVelocity, pAtm));
}

But your code is a bit confusing to me, it looks like you're making ParticleSystem inherit from Particle. That doesn't really make sense because ParticleSystem is not a Particle. ParticleSystem should store particles instead of being one. I think this weird inheritance is what confused you.

Related