I am tinkering with Phaser game engine. I have figured out how to color the sprite, so the next step is giving it a random color. How would I do that using an enum?
var colors = {
RED: 0xff0000,
GREEN: 0x00ff00,
BLUE: 0x0000ff
}
logo.tint = colors[Math.floor(Math.random() * colors.length)];
I just came to this problem today and able to get a random value by this:
var rand = Math.floor(Math.random() * Object.keys(colors).length);
var randColorValue = colors[Object.keys(colors)[rand]];
Here is a method I wrote in typescript that I used, remove types if you want to use with javascript.
function getRandomEnumValue<T>(anEnum: T): T[keyof T] {
//save enums inside array
const enumValues = Object.keys(anEnum) as Array<keyof T>;
//Generate a random index (max is array length)
const randomIndex = Math.floor(Math.random() * enumValues.length);
// get the random enum value
const randomEnumKey = enumValues[randomIndex];
return anEnum[randomEnumKey];
// if you want to have the key than return randomEnumKey
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With