Equation of a straight line
// Initial function modified by the suggestions of Franco Ponticelli public static inline function lineEquation(x1 : Float, x2 : Float, y0 : Float, y1 : Float, y2 : Float) { return (x2 - x1) * (y0 - y1) / (y2 - y1) + x1; } public static inline function lineEquationInt(x1 : Float, x2 : Float, y0 : Float, y1 : Float, y2 : Float) { return Math.round(lineEquation(x1, x2, y0, y1, y2)); }
What is this equation useful for? Anything that changes the values linearly.
>
Here's an example how to move a progress bar when you know the percent loaded:
progressBar.width = lineEquation (0, 530, percent, 0, 100);
0 - 530 means that the width of the progressBar will change from 0 to 530 when the percent will take values from 0 to 100.
>
Here's another example that will move a container on y axis by a scrollBar
var x1 = 0; var x2 = x1 - container.height + containerMask.height; var y0 = scrollBar.y; var y1 = 0; var y2 = y1 + containerMask.height - scrollBar.height; container.y = lineEquation (x1, x2, y0, y1, y2);
I find it useful because you don't have to think the formula again and again, you know visually what values to put in the function.
The math:
( x0 - x1 ) ( y0 - y1 ) ----------- = ----------- ( x2 - x1 ) ( y2 - y1 ) (x2-x1)*(y0-y1) x0 = ----------------- +x1 (y2-y1)
version #6827, modified 2009-08-20 06:23:26 by cristibaluta