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

Enhance the <div> with interactive content through dynamic updates on click within the same element

I am currently developing an Editor-Menu for a website administration. When I open admin.php, the Editor-Menu should be loaded into the #ausgabe div using the code $('#ausgabe').load('./admin-ajax/ajax2.php'). This functionality is work ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

Is it considered fundamentally inappropriate to call $scope.$digest within $scope.$on?

I recently inherited some AngularJS code, and my knowledge of both the codebase and Angular itself is limited. Within the code I inherited, there are instances where $scope.$digest is being called inside a $scope.$on method within a controller. Here's ...

Can jQuery effortlessly glide downward, come to a stop, continue downward, and then move upwards?

My webpage features a large table created and populated automatically every minute using ajax. The code structure is as follows: $(document).ready(function(){ setInterval(function(){ $.ajax({ //code to call backend, get the data, ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

Encountering the error message "undefined is not a function" while attempting to retrieve JSON data

I'm running into some issues with retrieving data from a PHP file. Upon calling the variable msg[0}, I'm getting an undefined error even though it should have been filled in during the JSON request. The JavaScript code is provided below, and you ...

Unable to display Three.JS OBJ Model

I am facing an issue with loading a .obj model in Three.js. I created the model in Cinema 4D, exported it with a scale of 1 meter, and tried to load it using OBJLoader in Three.js. However, even though there are no errors, the model is not showing up. Wh ...

A peaceful WCF service initiates a client callback whenever a server update occurs

In the process of developing a WCF RESTFUL service on top of a c++ console application, I am confronted with an issue. The client accesses this c++ application through my restful wcf service using a browser. Every time there is an update received by my w ...

When executing class methods, Ember.js encounters errors stating "method does not exist."

I am facing a situation where I need to trigger a model reload when a user clicks a refresh button. In the past, I successfully implemented this with Ember-Model. However, since migrating to Ember-Data, I am encountering an error when attempting to execute ...

Determine if a specific checkbox with a particular id has been selected using JQuery

Looking for assistance on how to determine if a checkbox with a specific ID is checked or unchecked. <input name="A" id="test" type="checkbox" value="A" /> <input name="B" id="test" type="checkbox" value="B" /> <input name="C" id="test1" t ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

Learn how to move to a new line when inputting data into a CSV file with JavaScript

My challenge involves taking an array of objects, for example: array=[hello, how, are, you], extracted from the document.innerHTML. I aim to write these objects to a CSV file using puppeteer and JavaScript, each on a new line. Although when using the sta ...

Guide on how to retrieve a value using image.onload on the client side

I have encountered an issue with exporting a png image from an svg element using Blob. The problem arises when clicking the anchor tag to export the image, as the content is not rendered due to the asynchronous method (image.onload()) being called after th ...

How can you determine if a domain belongs to Shopify when given a list of 98000 domain names using Node.js?

Is there a way to determine if a domain is operating on the Shopify e-commerce platform? I have been searching extensively but haven't found a reliable method. I possess an array containing 98,000 domain names and I am interested in utilizing node.js ...

Top method for handling chained ajax requests with jQuery

I'm facing a scenario where I have to make 5 ajax calls. The second call should only be made once the first call returns a response, the third call after the second completes, and so on for the fourth and fifth calls. There are two approaches that I ...

Is there a way to fetch and display property changes in Vue Material's md-dialog?

In the component hierarchy, there is a parent component containing a child, which further contains an md-dialog component. The dialog is opened from the parent component using the following code: ParentComponent.vue <template> <div> < ...

changing the RadioButtonList to preselect a default value

On a page, I have a pre-existing RadioButtonList where I want to make the second button checked by default instead of the first one. Since I am unable to edit the original control directly, it seems like I might need to achieve this using javascript on th ...

Prevent the box from closing automatically after submitting a form using jQuery

Despite my efforts to keep a simple dialog box open after submitting a form, it continues to close. I tried using the preventDefault method in jQuery, but it didn't solve the issue. Below is the code snippet: $(document).ready(function(e) { $(&apo ...

JQuery method for extracting a specific span's content from a div

I am faced with extracting specific text from a span within a div element. Below is the code snippet for my Div: '<div class="dvDynamic_' + pid + '"><p hidden="true">'+pid+'</p><span class="count_' + pid ...