map()
Math is great! I promise, you are going to get better at it, and you will find it absolutely necessary in art, life, and code. Keep at it, stay calm, and work on it, piece by piece.
BUT, one of the great promises of code and computers, is to make out life easier, not harder. To that extent, there are many functions, that will make your life easier not harder, as long as you know they exist, and know how to use them.
The map function (map()
) is a very useful function, that reduces the need to think about math.
As noticed on the reference page, this function takes 5 input parameters, all of data type Number.
The first input parameter is a value that you want mapped. This is typically some output from a complex algorithm, real-world data, mouse/user input, or random number generators. The map function then can take this input, and produce an output range that is appropriate for whatever the task is.
The second and third input parameters are the “expected input range”. This is the minimum and maximum values that you expect as possible at the input value. I.E. if you pass mouseX
to the first input parameter, the expected input range for the second two parameters would be 0
or the left side of the canvas, and width
or the right side of the canvas.
The last set of input parameters, are the output range that the function will map to. Following from the above example, lets say you want to adjust the size of an ellipse, you would specify in that fourth and fifth parameter, the smallest and largest values you want for the ellipse.
The following code, presents how the map function could be used to set the size of an ellipse, based on the mouse’s X position, as described above.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |