Connecting the dots

In this recipe we will show how to connect particles with lines and introduce another way of drawing particles.

Getting started

This recipe's code base is an example from the recipe Simulating particles flying on the wind (from Chapter 5, Building Particle Systems), so please refer to this recipe.

How to do it…

We will connect particles rendered as circles with lines.

  1. Change the number of particles to create inside the setup method:
    int numParticle = 100;
  2. We will calculate radius and mass of each particle as follows:
    float radius = Rand::randFloat(2.f, 5.f);
    float mass = radius*2.f;
  3. Replace the draw method inside the Particle.cpp source file with the following:
    void Particle::draw(){
     ci::gl::drawSolidCircle(position, radius);
     ci::gl::drawStrokedCircle(position, radius+2.f);
    }
  4. Replace the draw method inside the ParticleSystem.cpp source file as follows:
    void ParticleSystem::draw(){
     gl::enableAlphaBlending();
     std::vector<Particle*>::iterator it;
     for(it = particles.begin(); it != particles.end(); ++it){
      std::vector<Particle*>::iterator it2;
      for(it2=particles.begin(); it2!= particles.end(); ++it2){
       float distance = (*it)->position.distance( 
        (*it2)->position ));
       float per = 1.f - (distance / 100.f);
       ci::gl::color( ci::ColorA(1.f,1.f,1.f, per*0.8f) );
       ci::Vec2f conVec = (*it2)->position-(*it)->position;
       conVec.normalize();
       ci::gl::drawLine(
        (*it)->position+conVec * ((*it)->radius+2.f),
        (*it2)->position-conVec * ((*it2)->radius+2.f ));
      }
     }
     ci::gl::color( ci::ColorA(1.f,1.f,1.f, 0.8f) );
     std::vector<Particle*>::iterator it3;
     for(it3 = particles.begin(); it3!= particles.end(); ++it3){
      (*it3)->draw();
     }
    }

How it works…

The most interesting part of this example is mentioned in step 4. We are iterating through all the points, actually through all possible pairs of the points, to connect it with a line and apply the right opacity. The opacity of the line connecting two particles is calculated from the distance between these two particles; the longer distance makes the connection line more transparent.

How it works…

Have a look at how the particles are been drawn in step 3. They are solid circles with a slightly bigger outer circle. The nice detail is the connection line that we are drawing between particles that stick to the edge of the outer circle, but don't cross it. We have done it in step 4, where we calculated the normalized vector of the vectors connecting two particles, then used them to move the attachment point towards that vector, multiplied by the outer circle radius.

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.129.26.185