Hello,
Currently, while developing UI in Roblox, I find myself having to somehow convert different values of a specific range into values of another range. This can be tedious and not so easy to do with specific things.
I would like to have an inbuilt function to take care of this for me. Similar to the p5.js framework, there is a command known as map()
This command takes 5 arguments. (With an optional 6th).
- The iterator (could be the actual value such as mouse’s position)
- Minimum value for the mouse’s range
- Maximum value for the mouse’s range
- New minimum value for the mouse’s range to be mapped to
- New maximum value for the mouse’s range to be mapped to
- bool value to constrain the mapped value to the range set (just means that if you give a value less/more than the given bounds for that item, it will just return the minimum instead of a number outside the bounds of the new range.
The 6th value is optional and defaults to false, as long as your given iterator is within the given range for that iterator, there will be no problems.
I have recreated the code for this command in lua below:
Map Command Code
--// maps a given range from a specific iterator to a new range
local function map(n, start, stop, newStart, newStop, withinBounds)
local value = ((n - start) / (stop - start)) * (newStop - newStart) + newStart
--// Returns basic value
if not withinBounds then
return value
end
--// Returns values constrained to exact range
if newStart < newStop then
return math.max(math.min(value, newStop), newStart)
else
return math.max(math.min(value, newStart), newStop)
end
end
for i = 0, 600 do
print(map(i, 0, 600, 0, 255, true))
-->> Outputs the range 0-600 mapped between 0-255
end
I feel as though this function would be a very useful addition for graphical artists on Roblox as well as backend developers wishing to make their games work just this little bit more efficiently.
A quick use-case off the top of my head could be if a graphical user wanted to assign the mouse’s position within the screen to set the colour of the background between black and white or whatever colour range they wished. As they moved the mouse from 0 to 1000, they could get the mapped value of the mouse’s position between 0-255 so that they could get a gradient mapped over the whole x-axis of the screen.
Or a developer could use it to make simple harmonic motion with UI elements. A quick sketch up could look like this:
Harmonic Motion sketch
local angle = 0
while wait() do
local h = map(math.sin(angle), -1, 1, 0, 1)
uiElement.Size = UDim2.new(.1,0,h,0)
angle = angle + 0.1
end
All feedback is welcome.
Sincerely,
RoyallyFlushed