What is the best way to design a new class that will serve as the parent class for both of my existing classes, allowing them

I am facing a challenge with my programming classes. I have two classes, "Player" and "Enemy", each with similar methods and properties. I want them to inherit from a parent class that I'll create called "Game Object".

How can I approach creating this inheritance structure?

I am working in Javascript and have attempted to research on my own but haven't fully grasped the concept yet.

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 have not been able to achieve the desired results and would appreciate some guidance on how to proceed.

Answer №1

To achieve inheritance in ES6 classes, you can utilize the extends keyword:

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;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...

Steps for identifying if the line before in a textarea is blank

Is there a way to identify the structure of individual lines within a textarea? As an example, consider the following contents in my textarea: this is the first line in textarea 1234 this is the second line starting with 1234 this is the fourth line and ...

What could be causing the background image on my element to not update?

I'm attempting to utilize a single background image that is 3 pixels wide and 89 pixels tall. Each vertical stripe of 1 pixel will serve as the background for a different div. I had presumed that adjusting the background-position by -1px 0 and specif ...

Transferring data from PHP to JavaScript using AJAX

I'm currently working on a project that involves generating random numbers on both JavaScript and PHP pages, and I need to display them on the HTML page using JavaScript. So far, I have successfully set up both pages to generate random numbers. Howev ...

Changing Three.js from mouse interaction to a random movement pattern

Recently, I came across this interesting website with a background that lights up depending on the movement of your mouse. I was wondering if there is a way to make that illuminated spot move around on its own. If you want to see how it looks, check out th ...

Tips on creating a horizontal scrolling effect using the mouse

Is there a way to enable horizontal scrolling by holding down the mouse click, instead of relying on the horizontal scroll bar? And if possible, can the scroll bar be hidden? In essence, I am looking to replicate the functionality of the horizontal scroll ...

Guide to showing an uploaded image in a child component using Vue.js

Using the v-file-input component from Vuetify, I am able to upload images with the following code: <v-file-input label="Image" filled accept="image/png, image/jpeg, image/bmp" prepend-icon="mdi-camera" v-mod ...

How can I ensure that a button remains fixed at the bottom of a Material UI React Component?

I am currently working on developing a layout for a web application, and I have encountered an issue that I am struggling to resolve. The structure of my grid is as follows: My goal is to ensure that each section inside the card starts at the same point. ...

Is there a simple way to delete an element from a multidimensional array object in React JS?

In my current project using React Js, I'm facing an issue with removing an item that corresponds to the "product_option_value_id". The task at hand is to remove an item from the product_option_value (a child array object) if the given itemId matches t ...

Effective methods for synchronizing two dropdown menus with varied displays using React

Having a list of countries with specific key-value pairs, I am interested in creating two Dropdown lists. The first will display the keys, while the second will show the corresponding text values. The main objective is to provide the option to select eith ...

The Shopify storefront API's create cart mutation generates an HTML response when called

I recently started developing an e-commerce website using Next.js and Shopify's storefront API. I have successfully set up the connection and can list all the products from the API. However, I encountered an issue when attempting to add a product for ...

Exploring JSON data through key-value pairs

When faced with a de-serialized JSON object that has an arbitrary structure and mixed value types... var data = { 'a':'A1', 'b':'B1', 'c': [ {'a':'A2', 'b':true}, ...

Access the value within an object that contains an array and compare it with a different array

array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a3d2e6f7e1e6bcf1fdff">[email protected]</a>', group_ids: ["25"], username: 'test1'}, {id: ...

Is there a way to prevent pixels from being rendered outside of a designated rectangle in HTML5?

I'm looking to add screen-in-screen functionality to my HTML5 game, and I have an idea for how to approach it: //Function called every frame function draw(){ set a mask rectangle only draw pixels from the current frame that fall within this recta ...

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

Troubleshooting Appium error management is ineffective

As a newcomer to appium, I might have made some mistakes. I'm encountering a problem with appium while using wdio and jasmine. it('wtf', (done) => { client.init().element('someName').getText() // ^ here ...

Choosing specific information in Typescript response

I am encountering an issue with my HTML where it displays undefined(undefined). I have checked the data in the debugger and I suspect that there may be an error in how I am using the select data. Here is a snippet of the code: <div *ngIf="publishIt ...

AJAX Form Submission for CommentingAJAX allows for seamless form submission

Currently facing an issue with a form submission that is not displaying comments without refreshing the page. When the submit button is clicked, it redirects to the top of the page without executing any actions - no insertion into the database and subseque ...

What are the ways to activate an element in vue js?

Is there a way to modify the code so that the function triggers with just one click instead of two? export default { methods: { remove(){ $('.remove-me button').click( function() { removeItem(this); }); ...

How can markers be filtered on a Google Map API without the need to refresh the map?

I have created an Angular JS module that utilizes the Google Map API. The map is defined as a global variable, along with a global array for markers, and functions for managing these markers such as removing them, resetting the map, and adding new markers. ...