How to spawn random object on button press in Javascript

2 days ago 5
ARTICLE AD BOX

I am working on a Virtual pet javascript game for my website inspired by chao garden. I currently have a working spawner to create the pet, but it currently on randomizing which pet you get when you hit the spawn button. As it currently works, this function is called on button press:

function spawnChao() { let c = new Chao( Math.random() * 560, Math.random() * 360 ); chaos.push(c); }

The chao spawned is using properties from this class:

class Chao { constructor(x, y) { this.x = x; this.y = y; this.hunger = 50; this.happiness = 50; this.energy = 50; this.alignment = 0; // -100 dark → +100 hero this.speed = 1 + Math.random(); this.target = null; this.el = document.createElement("div"); this.el.classList.add("chao", "gerbomination"); garden.appendChild(this.el); }

"gerbomination" being the name of the only creature it currently spawns.

I tried using the following code in the function for a random output, but that stops the spawner from making anything entirely:

function spawnChao() { let c = new Chao( var creatures = ["gerbomination", "hero","dark"]; let r = () => Math.floor(Math.random() * creatures.length); Math.random() * 560, Math.random() * 360 ); chaos.push(c); }

What would be the best solution for this?

Read Entire Article