Skip to content

Monster Spawner

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 number of spawned monsters and check if we need to spawn more
    const stepSeconds = 5;
    const monstersToSpawn = 3;
    if (this.getSpawnedMonsters() < monstersToSpawn) {
        const config = { type: 'ogre', respawnMin: 15, respawnMax: 25 };

        // Spawn a normal monster after a few seconds
        this.spawnCounter += stepSeconds;
        const 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() {
    const myId = this.id;
    let spawnNr = 0;
    Server.searchnpcs({
        map: this.map,
        area: { x: this.x - 25, y: this.y - 25, w: 50, h: 50 }
    }).forEach(obj => {
        if (obj.spawner === myId) {
            spawnNr++;
        }
    });
    return spawnNr;
}


function spawnMonster(monsterType) {
    const 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)
    );
    const obj = {
        npcclass: 'mob',
        ani: 'player_idle',
        x: pos.x,
        y: pos.y,
        mobtype: monsterType,
        dontsave: true
    };
    const mob = this.map.addnpc(obj);
    if (mob) {
        mob.spawner = this.id;
    }
}