Search code examples
c++openglparticles

particle system: particle generation


I have a system that generates particles from sources and updates their positions. Currently, I have written a program in OpenGL which calls my GenerateParticles(...) and UpdateParticles(...) and displays my output. One functionality that I would like my system to have is being able to generate n particles per second. In my GenerateParticles(...) and UpdateParticles(...) functions, I accept 2 important parameters: current_time and delta_time. In UpdateParticles(...), I update the position of my particle according to the following formula: new_pos = curr_pos + delta_time*particle_vector. How can I use these parameters and global variables (or other mechanisms) to produce n particles per second?


Solution

  • You need to be careful, the naive way of creating particles will have you creating fractional particles for low values of n (probably not what you want). Instead create an accumulator variable that gets summed with your delta_time values each frame. Each frame check it to see how many particles you need to create that frame and subtract the appropriate amounts:

    void GenerateParticles(double delta_time) {
      accumulator += delta_time;
      while (accumulator > 1.0 / particles_per_second) {
        CreateParticle(...);
        accumulator -= 1.0 / particles_per_second;
      }  
    }
    

    Make sure you put some limiting in so that if the time delta is large you don't create a million particles all at once.