SmoothMove.cpp
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
1 2 #include "smoothMove.h" 3 4 SmoothMove::SmoothMove(const Vector3 &start, const Vector3 &end, const float time,float (*smoothMethod)(float)): 5 mStart(start), mEnd(end), mTotalTime(time),mCurrentMethod(smoothMethod) 6 { 7 mCurrentTime = 0; 8 mCurrent = mStart; 9 } 10 11 Vector3 SmoothMove::IterateFrame(const float time) 12 { 13 mCurrentTime+=time; 14 if(mCurrentTime>mTotalTime) 15 mCurrentTime=mTotalTime; 16 return CalculateCurrentPos(); 17 } 18 19 Vector3 SmoothMove::CalculateCurrentPos() 20 { 21 mCurrent.x = CalculatePos(mStart.x,mEnd.x,mCurrentTime,mTotalTime); 22 mCurrent.y = CalculatePos(mStart.y,mEnd.y,mCurrentTime,mTotalTime); 23 mCurrent.z = CalculatePos(mStart.z,mEnd.z,mCurrentTime,mTotalTime); 24 25 return mCurrent; 26 } 27 28 void SmoothMove::SetNewTarget(const Vector3 &end, const float time) 29 { 30 mStart = mCurrent; 31 mEnd = end; 32 mCurrentTime = 0; 33 mTotalTime = time; 34 } 35 36 bool SmoothMove::isEqual(float x, float y) 37 { 38 return abs(x-y)<0.000000001; 39 } 40 41 float SmoothMove::CalculatePos(float start, float end,float currentTime, float totalTime) 42 { 43 // we transform the currentTime value into a (0,1) range value that 44 // indicates the ammount of the travel we've done so far 45 float x = 1-(totalTime-currentTime)/totalTime; 46 47 // we make sure the method gives valid results at least for the beggining and end 48 assert(isEqual((*mCurrentMethod)(0),0)); 49 assert(isEqual((*mCurrentMethod)(1),1)); 50 51 // We interpolate the value 52 float current = (*mCurrentMethod)(x); 53 54 // we go back from (0,1) range to (start, end) range 55 current=current*(end-start)+start; 56 57 return current; 58 }