Jan
2
2012

Precalculated Sin Cos Arrays

In the old days (blitz basic, qbasic..) these lookup tables were quite useful!

Download test scene: (moving sphere..Note! saved with Unity3D v3.5)
mSinCosTables.unitypackage

Source: (javascript, attach it to some object to see it moving..)

// Precalculated SinCos - Unity3D version - mgear - http://unitycoder.com/blog/
// ORIGINAL SOURCE: "Jim" http://www.dbfinteractive.com/forum/index.php?topic=4772.0
#pragma strict

private var lookupTableSize:int=65536; // or 1024
private var mSin:float[]; // using native .NET arrays (see unity help page for ARRAY)
private var mCos:float[];
private var mconst:float;
private var c:float = 0;
private var maxrad:float = 2*Mathf.PI;

function Start ()
{
// init arrays
mCos = new float[lookupTableSize];
mSin = new float[lookupTableSize];
mconst = lookupTableSize / (2*Mathf.PI); // array index constant
// build lookup tables
var angle:float = 0;
for (var i:int=0;i<lookupTableSize;i++)
{
mSin[i] = Mathf.Sin(angle);
mCos[i] = Mathf.Cos(angle);
angle += 2*Mathf.PI/lookupTableSize;
}
}

// mainloop
function Update ()
{
//     normal maths
//    transform.position.x = Mathf.Cos(c)*5;
//    transform.position.y = Mathf.Sin(c)*5;
//    c+=0.05;

// precalculated
transform.position.x = getCos(c)*5;
transform.position.y = getSin(c)*5;
c = Mathf.Repeat(c+0.05,maxrad);
}

// helper functions
function getSin(radians:float) {return mSin[radians * mconst];}
function getCos(radians:float) {return mCos[radians * mconst];}


Related Posts

About the Author:

.fi

11 Comments + Add Comment

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Github Join Discord Twitch Instagram BlueSky

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.