Last active
February 7, 2019 06:50
-
-
Save cbscribe/592542568a1d6843da2972943069273e to your computer and use it in GitHub Desktop.
GDScript utility functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# add this as a singleton and access functions using | |
# util.<function_name> | |
extends Node | |
# choose a random item from an array | |
static func rand_choice(list): | |
return list[randi() % list.size()] | |
# choose a random integer in range (start, end-1) | |
static func rand_int(start, end): | |
return start + randi() % (end - start) | |
# Perform the Fisher–Yates shuffle dance to magically unsort given array | |
static func shuffle(array): | |
var size = array.size() | |
for i in range(size - 1): | |
swap(array, i, rand_int(i, size)) | |
return array | |
# Swap items of index i and j in given array | |
static func swap(array, i, j): | |
var tmp = array[i] | |
array[i] = array[j] | |
array[j] = tmp | |
return array | |
static func weighted_rand(weights): | |
# returns a random choice weighted by the given array | |
# ex: weights = [75,20,5] (3 items, ordered) | |
# sum up the weights | |
var sum = 0 | |
for weight in weights: | |
sum += weight | |
# select a random number | |
var num = rand_range(0, sum) | |
# loop through weights | |
for i in range(weights.size()): | |
if num < weights[i]: | |
return weights[i] | |
num -= weights[i] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment