|
Shifting & Scaling Numbers
"Shifting and scaling" is another way to say
adding and multiplying. But more, it describes the effect
of adding and multiplying on ranges of numbers. In the
tutorial a range of numbers is denoted "x:10->15"
which means that the variable x goes from 10 to 15.

To shift a range of numbers means to add a number (positive
or negative) to it. This moves the range, but doesn't change the distance
between the values.
To scale a range of numbers means to multiply
it by a number. This does change the distance between the values, and
also changes the end points unless they are at zero.
A general method for transforming
a source range x:A->B to a target range y:C->D
is:
- Shift the source range to
0 by subtracting A
- Scale to the target range
size.
The number to multiply by is (D-C)/(B-A) which is the
ratio of the range sizes.
- Shift the range to the desired place
by adding C.
The final form, then, of an equation that transforms x:A->B
to y:C->D is:
y = (x - A) * (D - C)/(B
- A) + C
Using Shifting & Scaling
in Animation
Ranges of numbers are worked with often in animation. For example, the
loop variable in a "repeat with" loop covers
a range of numbers. The possible locations of an adjustable slider
bar, the time elapsed since a certain start
time, the possible mouse locations, etc, all cover ranges
of numbers.
As an example of how shifting & scaling
is used, say you've got a slider bar that moves horizontally
and has a range loch:72->178. You want the slider
to control the rotation of a sprite with the range rot:1125->-45.
According to the steps above, you would:
- Subtract 72 to shift the range to zero.
loch - 72
- Scale the range, multiplying by targetRangeSize/sourceRangeSize
This would be (-45 - 1125)/(178 - 72) = -1170/106.0
(loch - 72) * -1170/106.0
- Shift the range by adding targetRangeStart
(loch - 72) * -1170/106.0 + 1125
The resulting expression is a linear
function.
property sp
property spSlider
on beginsprite( me)
sp = sprite( me. spritenum)
spSlider = sprite( 2)
end
on exitframe()
sp.rotation = (spSlider.loch
- 72) * -1170/106.0
+ 1125
end
Notice the 106.0
in the division, with a decimal. If you aren't familiar with the reason
for the decimal, see Integer Division.
If the values you want to shift & scale don't
have a limited range, find two reference values
and use those as the start and end values. A reference value
is a value in the source range for which you know the desired target value.
Extra for philomaths:
The shift & scale process described above relies on two
"reference values", usually the end points of
the ranges, to find a linear function. Although it comes at the
problem from a different angle, it is the same process used to find
the equation of a line, given two points. The points
are (range1_start, range2_start) and (range1_end, range2_end).
|