view game/js/projectile.js @ 36:a464bd43b76c 1.0.0

clean documentation rewrite
author ark
date 2026-10-21 22:34 +0200
parents 3f2811aebb3d
children
line wrap: on
line source

// projectiles: fly towards their target and damage it on arrival. p2 does
// no damage; it bursts where it lands and slows every monster nearby

window.MM = window.MM || {};

MM.projectile = (function () {
    "use strict";

    function create(tower, target, damage) {
        var def = tower.def;
        return {
            kind: def.projectile,
            speed: def.projectile_speed,
            x: tower.x,
            y: tower.y,
            tx: target.x,
            ty: target.y,
            target: target,
            damage: damage,
            slow: def.slow ? def.slow[tower.level - 1] : 0,
            slowTime: def.slow_time,
            splash: def.splash_radius || 0,
            angle: Math.atan2(target.y - tower.y, target.x - tower.x),
            done: false
        };
    }

    // home in on the target. if it died first, fly on to its last position
    // and disappear there without damage; a splash still bursts there.
    function update(p, game, dt) {
        var t = p.target;
        if (t && t.alive) {
            p.tx = t.x;
            p.ty = t.y;
        } else {
            t = null;
        }
        var dx = p.tx - p.x, dy = p.ty - p.y;
        var d = Math.hypot(dx, dy);
        var step = p.speed * dt;
        var reach = t ? Math.max(step, t.hitRadius) : step;
        if (d <= reach) {
            if (p.splash) {
                game.freeze(p.tx, p.ty, p.splash, p.slow, p.slowTime);
            } else if (t) {
                if (p.slow) MM.monster.slow(t, p.slow, p.slowTime);
                if (p.damage) game.damage(t, p.damage);
            }
            p.done = true;
            return;
        }
        p.angle = Math.atan2(dy, dx);
        p.x += dx / d * step;
        p.y += dy / d * step;
    }

    return { create: create, update: update };
})();