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.
To navigate in the 3D space, we will use MayaCamUI
covered in the Using MayaCamUI recipe in Chapter 2, Preparing for Development.
We will create an example animation of an object moving along the spline. Perform the following steps to do so:
#include "cinder/Rand.h" #include "cinder/MayaCamUI.h" #include "cinder/BSpline.h"
Vec3f mObjPosition; BSpline3f spline;
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 );
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 );
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);
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:
3.129.25.217