Advertisement

Occilate between two numbers

Started by February 24, 2003 12:26 PM
3 comments, last by MagTDK 21 years, 11 months ago
How can occilate between two numbers? For instance, any number between the value 0 and 255. Is there a math function that can accomplish this?
n( t ) = A * sin ( omega * t +phi )

A is amplitude,
omega is pulsation
phi is phase constant

play with this value and find the function you like more
A is them value you want the function to oscillate , note that the range is -a , a , so you have to filter values using an if statemente if ( n(t)<-a ) n(t) = a

place the function in a for loop with t as discretized variable


Advertisement
Yeah, sin(x) and cos(x) in the form of A*sin(nx) + c. Just solve for A, n and c so that it fits your regression pattern.

-- Exitus Acta Probat --
Let''s say your two numbers are A and B. Here''s how you would smoothly oscillate between them using a sinusoid:

#define NUMBER_OF_STEPS 256 // should be a power of 2 to avoid floating point inaccuracies

float STEP = 1.0f/NUMBER_OF_STEPS;
float t = 0.0f;
A = first number
B = second number

and then, every frame:

t += STEP;
if(t >= 1.0f) { t = 1.0f; STEP = -STEP; }
else if(t <= 0.0f) { t = 0.0f; STEP = -STEP; }

float f = cosf(t*PI/2);
Value = B + f*(A-B); // i.e. (f)*A + (1-f)*B;


Also, if you can get away with linearly interpolating between two numbers (A and B), instead of smoothly oscillating via a sinusoid, then you can simplify. Every frame:

t += STEP;
if(t >= 1.0f) { t = 1.0f; STEP = -STEP; }
else if(t <= 0.0f) { t = 0.0f; STEP = -STEP; }

Value = B + t*(A-B); // i.e. (t)*A + (1-t)*B;

Note that if you are simply looking to toggle between two numbers then simplify further by replacing the first three lines with this:

t = 1.0 - t;

Thanks guys for your help.

This topic is closed to new replies.

Advertisement