• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

GML Map Function (not to be confused with ds_maps)

samspade

Member
Below is a script which takes in a number and re-maps it from one range to another. Isn't that hard to do without the script, but I've wanted to do it often enough in one line of code that I thought I would put it here. For example, if you wrote map(.5, 0, 1, 0, 10); it would return 5 (the number halfway between 0 and 10. However, it also works for arbitrary ranges, negative ranges, positive to negative ranges, and so on. So, map(6, 0, 5, 51, 72), map(7, 1, -5, -10, 234), and map(450, -10, 1000, 0, 1) would all work.

Probably the most common useful version of this is for drawing health bars etc. easily map health to a percent, or a range, or straight to the gui coordinantes that you want. For example, gui_x_health = map(current_health, 0, max_health, gui_x_start, gui_x_end). It also works if you want to easily tie one variable (say health) to another (say size) where you could do: size = 5; health = map(size, 0, max_size, 0, max_health) or something like that.

I'm sure it already exists somewhere, but I looked for a Gamer Maker version and couldn't find one.

Code:
/// @description Re-maps a number from one range to another
/// @param value
/// @param lowerbound of current range
/// @param upperbound of current range
/// @param desiredlowerbound
/// @param desiredupperbound

var val = argument[0]; 
var lower_bound = argument[1]; 
var upper_bound = argument[2]; 
var desired_lower_bound = argument[3]; 
var desired_upper_bound = argument[4]; 

var total = upper_bound - lower_bound;
var percent = (val - lower_bound) / total;
//var new_val = lerp(desired_lower_bound, desired_upper_bound, percent);
var new_val = (percent * (desired_upper_bound - desired_lower_bound)) + desired_lower_bound;
return new_val;
Math isn't my strong suit, so let me know if this could be improved. It does rely on the standard lerp function, but I haven't run into any problems with this yet. [edited to remove lerp].
 
Last edited:

FrostyCat

Redemption Seeker
Except for the number of arguments not being locked down, it's pretty much the same thing with 8 additional assignments.
 
Top