Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I make a "map" function similar to JavaScript?

Asked by
unmiss 337 Moderation Voter
6 years ago
Edited 6 years ago

Hey there. I've been coding with JS recently, a little bit with the wonderful p5.js library. I'm wondering how I would go about converting the p5.js map function to Lua, specifically Roblox.

p5.js Description:

Re-maps a number from one range to another.

p5.js Parameters:

value: Number: the incoming value to be converted

start1: Number: lower bound of the value's current range

stop1: Number: upper bound of the value's current range

start2: Number: lower bound of the value's target range

stop2: Number: upper bound of the value's target range

withinBounds: Boolean: constrain the value to the newly mapped range

I'm just not exactly sure of the math or steps needed to get this to work in RbxLua. If someone could point me in the right direction that'd be fantastic!

PS: Here's a link to the reference page for it.

1 answer

Log in to vote
0
Answered by 6 years ago

I don't know how to explain the math, but here's the function:

function map(value, start1, stop1, start2, stop2, withinBounds)
    local range1 = stop1 - start1
    local range2 = stop2 - start2
    value = (value - start1) / range1 * range2 + start2
    return withinBounds and math.clamp(value, start2, stop2) or value
end
Ad

Answer this question