Thursday, June 26, 2014

Interpolate Between Two angles(SLerp) C++ example.

This example Will show you how to interpolate between two angles that is given in degrees in 2D world. This code can be modified to use to interpolate between two 2DVectors.

In here vector3D is not included. you should write a simple vector3d class.


#include <math.h>

float PI = 3.141592653589793;

float RadianToDegree = 180.0f/PI;
float DegreeToRadian = PI/180.0f;

const float Dot(const vector3D& from, const vector3D& to)
{
return ((from.getX() * to.getX()) + (from.getZ() * to.getZ()));
}

const float Length(const vector3D& vector)
{
return sqrt((vector.getX() * vector.getX()) + (vector.getZ() * vector.getZ()));
}

vector3D Slerp(const vector3D& from, const vector3D& to, const float step)
{
if (step == 0) return from;
if (from == to || step == 1.0f) return to;

float theta = acos(Dot(from, to)/(Length(from) * Length(to)));
//float thetaDegree = theta * RadianToDegree;

if (theta == 0) return to;

float sinTheta = sin(theta);
return (from * (sin((1 - step) * theta) / sinTheta)) + (to * (sin(step * theta) / sinTheta));
}

float CurveAngle2(float from, float to, const float step)
{
if (step == 0) return from;
if (from == to || step == 1.0f)
{
return to;
}

if (from == 0.0f)
{
from = 1.0f * DegreeToRadian;
}

if (to == 0.0f)
{
to = 1.0f * DegreeToRadian;
}

VBS2Fusion::vector3D fromVector(cos(from), sin(from), 0.0f);
VBS2Fusion::vector3D toVector(cos(to), sin(to), 0.0f);

VBS2Fusion::vector3D currentVector = Slerp(fromVector, toVector, step);
float angleRadian = atan2(currentVector.getZ(), currentVector.getX());
if (angleRadian < 0.0f)
{
angleRadian = 2 * PI + angleRadian;
}

return angleRadian;
}

No comments:

Post a Comment