DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
SmoothMove.cpp
// description of your code here
Usage:
Initialization:
SmoothMove* sm = new SmoothMove(start,end,0.1,SmoothMove::DescQuadraticMethod);
Every frame:
Vector3 currentPosition = sm->IterateFrame(evt.timeSinceLastFrame);
If you want to change the target at midflight:
Vector3 newTarget(0.5,2.0,0.1); // the new target position
sm->SetNewTarget(newTarget,0.4); // give it 0.4 seconds to go there
#include "smoothMove.h"
SmoothMove::SmoothMove(const Vector3 &start, const Vector3 &end, const float time,float (*smoothMethod)(float)):
mStart(start), mEnd(end), mTotalTime(time),mCurrentMethod(smoothMethod)
{
mCurrentTime = 0;
mCurrent = mStart;
}
Vector3 SmoothMove::IterateFrame(const float time)
{
mCurrentTime+=time;
if(mCurrentTime>mTotalTime)
mCurrentTime=mTotalTime;
return CalculateCurrentPos();
}
Vector3 SmoothMove::CalculateCurrentPos()
{
mCurrent.x = CalculatePos(mStart.x,mEnd.x,mCurrentTime,mTotalTime);
mCurrent.y = CalculatePos(mStart.y,mEnd.y,mCurrentTime,mTotalTime);
mCurrent.z = CalculatePos(mStart.z,mEnd.z,mCurrentTime,mTotalTime);
return mCurrent;
}
void SmoothMove::SetNewTarget(const Vector3 &end, const float time)
{
mStart = mCurrent;
mEnd = end;
mCurrentTime = 0;
mTotalTime = time;
}
bool SmoothMove::isEqual(float x, float y)
{
return abs(x-y)<0.000000001;
}
float SmoothMove::CalculatePos(float start, float end,float currentTime, float totalTime)
{
// we transform the currentTime value into a (0,1) range value that
// indicates the ammount of the travel we've done so far
float x = 1-(totalTime-currentTime)/totalTime;
// we make sure the method gives valid results at least for the beggining and end
assert(isEqual((*mCurrentMethod)(0),0));
assert(isEqual((*mCurrentMethod)(1),1));
// We interpolate the value
float current = (*mCurrentMethod)(x);
// we go back from (0,1) range to (start, end) range
current=current*(end-start)+start;
return current;
}





