2

I have two classes, one is called "Player", the other one is called "Enemy". They both have similar methods and properties and I want them to inherit from a parent class which I'll create and call "Game Object".

How do I go about creating it?

This code is written in Javascript, I've tried to research it myself but didn't manage to understand it very well.

class Enemy
{
    constructor(sprite, positionX, positionY, speed)
    {
        this.sprite = sprite;
        this.positionX = positionX;
        this.positionY = positionY;
        this.speed = speed;
        this.direction = Math.floor(Math.random()*7) + 1;
        this.direction *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
        this.active = false;
    }
    getCenterPoint()
    {
        return new Point(this.positionX + 16, this.positionY + 16);
    }
}

class Player
{
    constructor(sprite, positionX, positionY, speed)
    {
        this.sprite = sprite;
        this.positionX = positionX;
        this.positionY = positionY;
        this.speed = speed;
        this.animationFrame = true;
    }
        getCenterPoint()
    {
        return new Point(this.positionX + 16, this.positionY + 16);
    }
}   

I couldn't manage to get the results that I wanted and need some guidance.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Kfir
  • 23
  • 2

1 Answers1

0

You can use the extends keyword for inheritance in ES6 classes:

class GameObject {
  constructor(sprite, positionX, positionY, speed) {
    this.sprite = sprite;
    this.positionX = positionX;
    this.positionY = positionY;
    this.speed = speed;
  }
  getCenterPoint() {
    return new Point(this.positionX + 16, this.positionY + 16);
  }
}

class Enemy extends GameObject {
  constructor(...props) {
    super(...props);
    this.direction = Math.floor(Math.random() * 7) + 1;
    this.direction *= Math.floor(Math.random() * 2) == 1 ? 1 : -1;
    this.active = false;
  }
}

class Player extends GameObject {
  constructor(...props) {
    super(...props);
    this.animationFrame = true;
  }
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79