Jamie Anacleto
Jamie Anacleto

Reputation: 55

generate sequential strings in javascript

Im making a javascript game, and I want to generate enemies, but this does not seem to work

var Monster = function(x,y) {
    this.x = x;
    this.y = y;
};

var spawnMonsters = function() {
    for(var i = 0; i < spawn; i++) {
        var name = "Monster";
        name += i;
        name = new Monster(Math.random()*canvas.width-16,0); 
    }     
};

help please? Though I can generate multiple enemies by hard-coding each monster name. such as Monster2=new Monster(Math.random()*canvas.width-16,0); Monster3=...... etc

Upvotes: 0

Views: 368

Answers (2)

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

In javascript you cannot use "variable variables" as you could do, for example, in PHP.

You could try this:

var monsters = [];

function spawn(num) {
  for (var i = 0; i < num; ++i) {
    monster.push(new Monster(Math.random() * canvas.width - 16, 0));
  }
}

now monsters will be an array of all the monsters you spawned.

Upvotes: 3

Hydroid
Hydroid

Reputation: 109

You can genarate Strings like:

function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for( var i=0; i < 5; i++ )
    text += possible.charAt(Math.floor(Math.random() * possible.length));

return text;
}

Upvotes: 0

Related Questions