I'm very new to Javascript, and what I'm about to ask is probably very rudimentary, but I'm stuck on a project, and I'd like some help.
Basically I'm doing a small Javascript project, where I want there to be some enemies. In the beginning there will be 0 enemies, and then as time goes on, there might be created more enemies. I was thinking that whenever an enemy is created, I should create it as an object, and then store it in an array containing all the active enemies in game. Then, later on, I could remove enemies from the array, that needed to be removed.
This is the function that creates my enemy objects:
function enemy(name, strength, rarity, estTime, success, remTime, Id){ this.name = name; this.strength = strength; this.rarity = rarity; this.estTime = estTime; this.success = success; this.remTime = remTime; this.Id = Id; }
So, I could then create some enemies like this:
var enemy1 = new enemy("Bob", 1, "Common", 100, 1, 30, 1) var enemy2 = new enemy("Cow", 22, "Rare", 50, 10, 40, 2) var enemy3 = new enemy("Pig", 333, "Epic", 25, 10, 50, 3)
Then I could create an array of enemies, and put my 3 enemies into that array:
var enemies = []; enemies = [enemy1, enemy2, enemy3];
All fine and dandy when I'm doing this manually, but the problem emerges when I want to try to get the code to automatically create some more enemies. Say I wanted to create an enemy everytime a button was pushed by the user. The name enemy would get some name, strength, rarity whatever, and the next Id in line (in this case 1, 2 and 3 are being used, so the next would be 4). I was thinking I could do it something like this, but this doesn't work:
enemy[enemies.length + 1] = new enemy("Dog", 444, "Epic", 13, 100, 60, 4); enemies.push(enemy + [enemies.length + 1]);
I was hoping that this would create an object called "enemy4" with with name, id and whatever I just typed in, and then add that object to the array of enemies.
But this obviously doesn't work. I hope you guys understand the problem, and any help is greatly appreciated. I realize that I'm probably just approaching this all wrong, and that there probably exists a much simpler way to do this.
Thanks!
EDIT: Yep, answer was very simple, got it now. Thanks!
var enemies = [
new enemy(/*params here*/),
new enemy(/*params here*/),
new enemy(/*params here*/),
new enemy(/*params here*/),
new enemy(/*params here*/)
];
Then later:
enemies.push(
new enemy(/*params here*/)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.