Handy Conversion Functions

Here is a small set of handy utilities from David Shute.

// ******************************************************************* 

function vecToStr(vect, dp)
{
    //returns the given vector as a string in the form "(x, y, z)"
    //Also accepts an optional parameter representing the number of
    //decimal places to display the results to (int) 

    if (dp != null)
        return "(" + vect.x.toFixed(dp) + ", " + vect.y.toFixed(dp) + ", "
                                                               + vect.z.toFixed(dp) + ")";
    else
        return "(" + vect.x + ", " + vect.y + ", " + vect.z + ")";
} 

// ******************************************* 

function rotToStr(rot, dp)
{
    //returns the given rotation as a string in the quaternion form "(x, y, z, w)"
    //Also accepts an optional parameter representing the number of
    //decimal places to display the results to (int).
    //To create a string using the Euler values, please use rotToStrEuler() 

    if (isNaN(dp))
        return "(" + rot.x + ", " + rot.y + ", " + rot.z + ", " + rot.w + ")";
    else
        return "(" + rot.x.toFixed(dp) + ", " + rot.y.toFixed(dp) + ", "
                          + rot.z.toFixed(dp)  + ", " + rot.w.toFixed(dp)+ ")";
}     

// ******************************************* 

function rotToStrEuler(rot, dp)
{
    //returns the given rotation as a string in the Euler form "(x, y, z)"
    //Also accepts an optional parameter representing the number of
    //decimal places to display the results to (int).
    //To create a string using the quaternion values, please use rotToStr() 

    if (dp != null)
        return "(" + rot.eulerX.toFixed(dp) + ", " + rot.eulerY.toFixed(dp)
                                                   + ", " + rot.eulerZ.toFixed(dp) + ")";
    else
        return "(" + rot.eulerX + ", " + rot.eulerY + ", " + rot.eulerZ + ")";
}     

// *******************************************

function clamp(value, min, max)
{
    //returns a number representing the given value clamped
    //between the specified high and low bounds. 

    return Math.min(Math.max(value, min), max);
} 

// *******************************************


Special thanks to David for sharing these useful tidbits.

Leave a Comment

You must be logged in to post a comment.