Monster Spawner
A script for monster spawning needs to check each few seconds how many monsters there are, and add more if they have been killed by players:
function onCreated() {
this.name = "";
this.nonblocking = true;
this.spawncounter = 0;
this.settimeout(1);
}
function onTimeout() {
// Calculate nr of spawned numbers and check if we need to spawn more
let stepSeconds = 5;
let monsterstospawn = 3;
if (this.getSpawnedMonsters() < monsterstospawn) {
let config = { "type": "ogre", "respawnmin": 15, "respawnmax": 25},
// Spawn a normal monster after a few seconds
this.spawncounter += stepSeconds;
let respawntime = config.respawnmin + Math.random() * (config.respawnmax - config.respawnmin);
if (this.spawncounter > respawntime) {
this.spawncounter = 0;
this.spawnMonster(config.type);
}
}
this.settimeout(stepSeconds);
}
function getSpawnedMonsters() {
var myid = this.id;;
var spawnnr = 0;
Server.searchnpcs({map:this.map, area:{x:this.x-25, y:this.y-25, w:50, h:50}}).forEach(function(obj) {
if (obj.spawner == myid)
spawnnr++;
});
return spawnnr;
}
function spawnMonster(monstertype) {
let pos = (monstertype == "guard"? {x:this.x, y:this.y} : this.map.randompos({x:this.x-10, y:this.y-6, w:20, h:12}, true));
let obj = {
npcclass: "mob",
ani: "player_idle",
x: pos.x,
y: pos.y,
mobtype: monstertype,
dontsave: true
};
let mob = this.map.addnpc(obj);
if (mob)
mob.spawner = this.id;
}