Enemy.js 2.08 KB
Newer Older
1 2 3 4 5 6 7 8
import GameObject from "./GameObject.js";

const DEFAULT_VELOCITY = 1,
  DEFAULT_HEALTH = 100,
  DEFAULT_WIDTH = 50,
  DEFAULT_HEIGHT = 50,
  DEFAULT_DAMAGE = 10,
  DEFAULT_HIT_BOX_RADIUS = 30,
9 10 11 12 13
  DEFAULT_ENEMY_COLOR = "#3f0d76",
  DEFAULT_ENEMEY_TIP_COLOR = "#d2ccf3",
  DEFAULT_ENEMY_HEALTH_COLOR = "#d2ccf3",
  DEFAULT_ENEMY_HEALTH_WIDTH = 10,
  DEFAULT_ENEMY_HEALTH_RADIUS = 50;
14 15 16 17 18

class Enemy extends GameObject {

  constructor(x, y, direction) {
    super(x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_HIT_BOX_RADIUS,
19 20
      DEFAULT_VELOCITY, direction, DEFAULT_ENEMY_COLOR);
    this.focus = false;
21 22 23 24 25 26
    this.health = DEFAULT_HEALTH;
    this.damage = DEFAULT_DAMAGE;
  }

  draw(context) {
    context.save();
27 28 29 30 31 32 33 34 35 36 37 38
    // Draw health bar  if focused
    context.translate(this.x, this.y);
    if (this.focus === true) {
      context.strokeStyle = DEFAULT_ENEMY_HEALTH_COLOR;
      context.lineWidth = DEFAULT_ENEMY_HEALTH_WIDTH;
      context.beginPath();
      context.arc(0, 0, DEFAULT_ENEMY_HEALTH_RADIUS, 0, 3.6 * this.health *
        Math.PI / 100);
      context.stroke();
      context.closePath();
    }
    // Draw enemy
39 40
    context.fillStyle = this.color;
    context.beginPath();
41
    context.rotate((90 + this.direction) * Math.PI / 180);
42 43 44
    context.moveTo(0, -this.height / 2);
    context.lineTo(-(this.width / 2), this.height / 2);
    context.lineTo(this.width / 2, this.height / 2);
45
    context.fill();
46
    context.closePath();
47 48 49 50 51 52
    // Draw tip
    context.fillStyle = DEFAULT_ENEMEY_TIP_COLOR;
    context.beginPath();
    context.moveTo(0, -this.height / 2);
    context.lineTo(-(this.width / 4), 0);
    context.lineTo(this.width / 4, 0);
53
    context.fill();
54
    context.closePath();
55 56 57
    context.restore();
  }

58 59 60 61 62 63 64 65
  setFocus() {
    this.focus = true;
  }

  removeFocus() {
    this.focus = false;
  }

66 67 68 69 70 71 72 73 74 75
  static createEnemy(rangeX, rangeY, targetX, targetY) {
    let xPos = parseInt(Math.random() * rangeX),
      yPos = parseInt(Math.random() * rangeY),
      direction = Math.atan2(targetY - yPos, targetX - xPos) * 180 / Math.PI;
    return new Enemy(xPos, yPos, direction);
  }

}

export default Enemy;