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
-
What does not seem to work? What do you expect your code to do vs what is happening?Evan Davis– Evan Davis2013年04月03日 15:47:52 +00:00Commented Apr 3, 2013 at 15:47
2 Answers 2
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
Matteo Tassinari
18.6k8 gold badges65 silver badges85 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
drquicksilver
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.Jamie Anacleto
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); } };
Matteo Tassinari
In your function, it is not clear from where
monsterImage does come.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;
}
Comments
lang-js