Useful GMS2 Code Snippets
A page of useful code snippets.
approach script:
I call this “subcompact approach script”
var x += clamp(target-x, -max_spd, max_spd);
In function form:
// approach(value, target, amount)
return argument0 + clamp(argument1 - argument0, -argument2, argument2);
debug helper script:
var str = "";
for(var i=0; i<argument_count; i++) {
str += string(argument[i]);
}
show_debug_message(str);
This script makes it easier to write debug messages by automatically stringifying the arguments. e.g. instead of:show_debug_message("X: " + string(x) + " Y: " + string(y));
use scr_debug("X: ", x, " Y: ", y);
ds_maps: iterating through a map:
var key = ds_map_find_first(<ds_map>);
while(not is_undefined(key)) {
var value = ds_map_find_value(<ds_map>, key);
// do stuff
key = ds_map_find_next(<ds_map>, key);
}
babyjeans version:
for(var key=ds_map_find_first(<ds_map>); not is_undefined(key); key=ds_map_find_next(<ds_map>, key)) {
var value = ds_map_find_value(<ds_map>, key);
// do stuff
}
IDE detect:
Detect if the code is running inside the IDE (as this sometimes breaks extensions):
if(debug_mode) return true; // if debug_mode, we’re definitely in IDE
if(code_is_compiled()) return false; // if compiled, we’re definitely not
if(parameter_count() == 3 and parameter_string(1) == “-game”) return true; // this tests for the IDE’s runner
return false; // I guess not
JSON: loading from file:
var buff = buffer_load(<filename>);
map = json_decode(buffer_read(buff, buffer_text));
buffer_delete(buff);
With error checking:
var buff = buffer_load(<filename>);
map = json_decode();
if(map == -1) {
// json decode error
}
buffer_delete(buff);
JSON: saving to file:
var str = json_encode(<map_name>);
var buff = buffer_create(string_byte_length(str), buffer_fixed, 1);
buffer_write(buff, buffer_text, str);
buffer_save(buff, <filename>);
buffer_delete(buff)
Singleton: pattern (with error popup in debug mode):
if(instance_number(object_index) > 1) {
if(debug_mode) {
show_error("More than one "+object_get_name(object_index)+" exists in "+room_get_name(room), true);
}
else {
instance_destroy();
exit;
}
}
This code snippet prevents more than one instance from being in a given room (e.g. in case of accidentally placing a persistent object twice, or returning to a room containing a persistent object). Either shows an error in debug mode, or silently destroys the instance that tries to be created.
Wrap (or handling negative modulo)
Wrapping between 0 and max:
/// wrap (value, max)
return (argument0 % argument1 + argument1) % argument1;
Some work would be needed to make this work with any (including negative) values; or a range