Another useful function is the constrain function (constrain()
), which, constrains an input parameter’s value to be within the min and max values supplied in the second and third parameters.
This can be useful for drawing, and protecting output values from “going out of range”.
The following code is adapted from the p5 site, and demonstrates using constrain to keep a ball, whose position is dictated by the mouse, between two lines on a canvas.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |