Enemy.js 1.27 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
const DEFAULT_SPEED = 1,
  DEFAULT_HEALTH = 100,
  DEFAULT_WIDTH = 20,
  DEFAULT_HEIGHT = 20,
  DEFAULT_DAMAGE = 10,
  DEFAULT_HIT_BOX_RADIUS = 30;

class Enemy {

  constructor(x, y, direction) {
    this.x = x;
    this.y = y;
    this.width = DEFAULT_WIDTH;
    this.height = DEFAULT_HEIGHT;
    this.speed = DEFAULT_SPEED;
    this.health = DEFAULT_HEALTH;
    this.damage = DEFAULT_DAMAGE;
    this.direction = direction;
  }

  update(target, adjustment) {
    this.direction = Math.atan2(target.y - this.y, target.x - this.x);
    this.x = this.x + Math.cos(this.direction) * this.speed * adjustment;
    this.y = this.y + Math.sin(this.direction) * this.speed * adjustment;
  }

  isHitBy(pos) {
    let distance = this.distanceTo(pos);
    if (distance <= DEFAULT_HIT_BOX_RADIUS) {
      return true;
    }
    return false;
  }

  distanceTo(target) {
    let deltaX = Math.abs(this.x - target.x),
      deltaY = Math.abs(this.y - target.y);
    return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
  }

  static createEnemy(area) {
    let xPos = parseInt(Math.random() * area.width),
      yPos = parseInt(Math.random() * area.height),
      direction = Math.atan2(area.center.y - yPos, area.center.x - xPos);
    return new Enemy(xPos, yPos, direction);
  }

}

export default Enemy;