Adding randomness

Let's add a bit of unpredictability to this by using the almighty random functions. To use them in Cinder, you have to include a header file that contains the necessary code:

#include "cinder/Rand.h"

Add this in the beginning of the BasicAnimationApp.cpp file. Next, we need to calculate random target position in the setup() method implementation:

void BasicAnimationApp::setup() {
  currentPosition = Vec2f(0,0);
  targetPosition.x = Rand::randFloat(0, getWindowWidth());
  targetPosition.y = Rand::randFloat(0, getWindowHeight());
  circleRadius = 100;
}

Now each time you run the application, a different end position will be calculated and the circle will fly to a different place on the screen.

Let's change the current position of the circle to something random as well:

void BasicAnimationApp::setup() {
  currentPosition.x = Rand::randFloat(0, getWindowWidth());
  currentPosition.y = Rand::randFloat(0, getWindowHeight());
  targetPosition.x = Rand::randFloat(0, getWindowWidth());
  targetPosition.y = Rand::randFloat(0, getWindowHeight());
  circleRadius = 100;
}

Compile and run the application to see the change.

It might seem a bit boring to see just one random animation after you have opened an application. People usually expect something more. So how about we calculate a new random end position as the circle reaches its current end position? Ok, let's do that! Add the following piece of code in the update() method implementation just after currentPosition = targetPosition - difference;:

if ( currentPosition.distance(targetPosition) < 1.0f ) {
  targetPosition.x = Rand::randFloat(0, getWindowWidth());
  targetPosition.y = Rand::randFloat(0, getWindowHeight());
}

Comment out or delete the following highlighted lines from the draw() method:

gl::clear( Color( 0, 0, 0 ) );
//currentPosition.x++;
//circleRadius--;
gl::drawSolidCircle( currentPosition, circleRadius );

Compile and run our application. This is a bit more interesting, but still it needs something more to be complete.

Adding randomness

How about we try to handle more than one circle on the screen? It would be worth explaining how to create a particle system as a separate class, but this won't fit in the scope of this book, so we will continue to make some changes in the same file.

..................Content has been hidden....................

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