GameObject.js 1.13 KB
Newer Older
Alexander Bazo committed
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 51 52
const schema = require('@colyseus/schema');
const Schema = schema.Schema;

class GameObject extends Schema {

  constructor(x, y, width, height, hitBoxRadius, velocity, direction, color) {
    super();
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.hitBoxRadius = hitBoxRadius;
    this.velocity = velocity;
    this.direction = direction;
    this.color = color;
  }

  update(delta) {
    if(this.velocity === 0) {
      return;
    }
    this.x += this.velocity * Math.cos(this.direction * Math.PI / 180);
    this.y += this.velocity * Math.sin(this.direction * Math.PI / 180);
  }

  isHitBy(object) {
    let distance = this.distanceTo(object);
    if (distance <= this.hitBoxRadius) {
      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);
  }

}

schema.defineTypes(GameObject, {
  x: "number",
  y: "number",
  width: "number",
  height: "number",
  velocity: "number",
  direction: "number",
  color: "string"
});

module.exports = GameObject;