Question

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?

Was it helpful?

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.

OTHER TIPS

The number of particles emitted at a frame can be computed by:

double n = delta_time * frequency
int i = (int)n;
f = n - i;

Basically you can emit i particles.

The fractional part f can be accumulated for the later frames. When it accumulates greater than one you can emit the integral number of particles:

f_sum += f;
if (f_sum > 1.0) {
    int j = (int)f_sum;
    f_sum -= j;
    i += j;
}

However, the following is another interesting solution for fractional number of particle.

By using a pseudo random number generator (PRNG), we can use it to determine whether a particle should be emitted:

if (f >= r()) // Assumes r() is a PRNG generating a random value in [0, 1) 
    i++;

This approach is useful when the frequency changes respect to time. And it eliminates the need of storing an additional variable.

Another beauty of this approach is that, the particle system will look less uniform. For example, if the frequency is 1.5 and delta time is 1, using the first approach, the frames will emit a sequence of 1, 2, 1, 2, ... particles. The second approach can break this pattern.

Besides, you may use of modf() to extract the integral and fractional part of a floating point number.

You just need to create n * delta_time particles in GenerateParticles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top