Simulating particles flying in the wind

In this recipe, we will explain how you can apply Brownian motion to your particles. Particles are going to behave like snowflakes or leaves flying in the wind.

Getting ready

In this recipe we are going to use the code base from the Creating a particle system in 2D recipe.

How to do it…

We will add movement to particles calculated from the Perlin noise and sine function. Perform the following steps to do so:

  1. Add the necessary headers.
    #include "cinder/Perlin.h"
  2. Add properties to your application's main class.
    float    mFrequency;
    Perlin    mPerlin;
  3. Set the default value inside the setup method.
    mFrequency = 0.01f;
    mPerlin = Perlin();
  4. Change the number of the particles, their radius, and mass.
    int numParticle = 300;
    float radius = 1.f;
    float mass = Rand::randFloat(1.f, 5.f);
  5. At the beginning of the update method, add the following code snippet:
    Vec2f oscilationVec;
    oscilationVec.x = sin(getElapsedSeconds()*0.6f)*0.2f;
    oscilationVec.y = sin(getElapsedSeconds()*0.2f)*0.1f;
    std::vector<Particle*>::iterator it;
    for(it = mParticleSystem.particles.begin(); it != mParticleSystem.particles.end(); ++it ) {
      Vec2f windForce = mPerlin.dfBm( (*it)->position * mFrequency );
        (*it)->forces += windForce * 0.1f;
        (*it)->forces += oscilationVec;
    }

How it works…

The main movement calculations and forces are applied in step 5. As you can see we are using the Perlin noise algorithm implemented as a part of Cinder. It provides a method to retrieve Brownian motion vectors for each particle. We also add oscilationVec that makes particles swing from left-to-right and backwards, adding more realistic behavior.

How it works…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.68.159