0

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

OptimizedQuery
1,26011 silver badges21 bronze badges
asked Apr 3, 2013 at 15:44
1
  • What does not seem to work? What do you expect your code to do vs what is happening? Commented Apr 3, 2013 at 15:47

2 Answers 2

3

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.

answered Apr 3, 2013 at 15:48
Sign up to request clarification or add additional context in comments.

3 Comments

Well you can use variable variables, either by using eval or by poking them into the scope object concerned (e.g. window in a browser). However you shouldn't do that for various reasons, so this approach is a much better one.
Thanks Matteo! lastly, how can I use that array of monsters to be drawn by this function var drawMonsters=function(){ for (var i=0;i<spawn;i++){ var name = "Monster"; name+=i; ctx.drawImage(monsterImage, name.x, name.y); } };
In your function, it is not clear from where monsterImage does come.
0

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;
}
answered Apr 3, 2013 at 15:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.