Animating along a path

In this recipe, we will learn how to draw a smooth B-spline in the 3D space and animate the position of an object along the calculated B-spline.

Getting ready

To navigate in the 3D space, we will use MayaCamUI covered in the Using MayaCamUI recipe in Chapter 2, Preparing for Development.

How to do it…

We will create an example animation of an object moving along the spline. Perform the following steps to do so:

  1. Include necessary header files.
    #include "cinder/Rand.h"
    #include "cinder/MayaCamUI.h"
    #include "cinder/BSpline.h"
  2. Begin with the declaration of member variables to keep the B-spline and current object's position.
    Vec3f       mObjPosition;
    BSpline3f   spline;
  3. Inside the setup method prepare a random spline:
    mObjPosition = Vec3f::zero();
    
    vector<Vec3f> splinePoints;
    float step = 0.5f;
    float width = 20.f;
    for (float t = 0.f; t < width; t += step) {
     Vec3f pos = Vec3f(
      cos(t)*randFloat(0.f,2.f),
      sin(t)*0.3f,
      t - width*0.5f);
     splinePoints.push_back( pos );
    }
    spline = BSpline3f( splinePoints, 3, false, false );
  4. Inside the update method, retrieve the position of the object moving along the spline.
    float dist = math<float>::abs(sin( getElapsedSeconds()*0.2f ));
    mObjPosition = spline.getPosition( dist );
  5. The code snippet drawing our scene will look like the following:
    gl::enableDepthRead();
    gl::enableDepthWrite();
    gl::enableAlphaBlending();
    gl::clear( Color::white() );
    gl::setViewport(getWindowBounds());
    gl::setMatrices(mMayaCam.getCamera());
    
    // draw dashed line
    gl::color( ColorA(0.f, 0.f, 0.f, 0.8f) );
    float step = 0.005f;
    glBegin(GL_LINES);
    for (float t = 0.f; t <= 1.f; t += step) {
      gl::vertex(spline.getPosition(t));
    }
    glEnd();
    
    // draw object
    gl::color(Color(1.f,0.f,0.f));
    gl::drawSphere(mObjPosition, 0.25f);

How it works…

First, have a look at step 3 where we are calculating a B-spline through points with coordinates based on the sine and cosine functions and some random points on the x axis. The path is stored in the spline class member.

Then we can easily retrieve the position in 3D space at any distance of our path. We are doing this in step 4; using the getPosition method on the spline member. The distance on the path is been passed as a float value in the range of 0.0 to 1.0 where 0.0 means the beginning of the path and 1.0 means the end.

Finally, in step 5 we are drawing an animation as a red sphere traveling along our path, represented as a black dashed line, as shown in the following screenshot:

How it works…

See also

  • The Aligning camera motion to path recipe
  • The Animating text around curves recipe in Chapter 7, Using 2D Graphics
..................Content has been hidden....................

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