What is the proper way to implement the .render and .animate functions within an object class?

After seven days of searching for a solution, I am determined to create a simple game by calling for an Object.

My vision is to develop a modular game structure, starting with the scene in the usual way:

main.js:

var scene, controls, camera, renderer;
var SCREEN_WIDTH, SCREEN_HEIGHT;
.....

var customObject;

init();
animate();

function init() {
    .....
    customObject = new GameElement();
    .....
}


function animate() {
    .....
}

function render() {
    ......
}

Next, I introduce my Player.js class:

function GameElement() {
    var character;
    this.loader = new THREE.JSONLoader();

    this.loader.load(

        'obj/models/game_model.json',
        function ( geometry, materials ) {

            var material = new THREE.MultiMaterial( materials );
            var character = new THREE.Mesh( geometry, material );
            character.position.set(0, 0, 0);

            character.castShadow = true;
            character.receiveShadow = false;

            scene.add( character );

        }
    );

}

GameElement.prototype.animate = function() {

    this.character.rotation.y -= 0.5;

}

In the initial code block, a new object is created:

customObject = new GameElement();

Everything seems to be functioning properly - the model loads, textures load, but there is one hurdle I can't overcome:

Within the Player class, I aim to define the render() and animate() functions for the Player Object, so that when the Player object is invoked in the main file (main.js), it will appear on the scene and animate based on these internal methods.

I am seeking guidance on the correct approach to creating a new Object with all its properties intact. Please assist me with this dilemma.

Answer №1

If you want to avoid getting undefined in your animate method when calling this.bobby, make sure to declare it as this.bobby in your constructor:

function Player() {
    this.bobby = null; // was: var bobby;
    this.loader = new THREE.JSONLoader();

However, this step may not be necessary.

To trigger certain code just before an object is rendered, you can define an onBeforeRender method for that object. The renderer.render method automatically invokes onBeforeRender for each object it renders, so in your scenario, you would define it for your this.bobby object.

(Definition:

onBeforeRender( renderer, scene, camera, geometry, material, group )
)

Here's an illustration:

function Player() {
    var bobby = null;
    this.loader = new THREE.JSONLoader();

    this.loader.load( '...',
        function ( geometry, materials ) {    
            // the rest of your code is fine
            bobby = new THREE.Mesh(...);
            bobby.onBeforeRender = function(){
                // note that in this callback, "this" now refers to the "bobby" object
                this.rotation.y -= 0.5;
            };
        }
    );    
}

There is potential for optimization in this approach, but the improvements are up to you.

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

Reloading the page using ajax technology

What is the best way to handle logging out on a webpage without reloading the page? Thanks in advance!) My perspective: def logout(request): auth.logout(request) html = render(request, 'base.html') return html Using Ajax: $('a[hre ...

Run a function upon clicking a button in JavaScript

Could someone please help me figure out what I am doing incorrectly in the code below? I am attempting to trigger a function when a button is clicked. The HTML: <button id="btn1">Press me!</button> <input type="button" id="btn2" value="Pr ...

The 3D formula for calculating the distance between a point and a line

Can anyone provide me with a computer program or algorithm that calculates the distance between a point and a line in a three-dimensional space? The program can be written in JavaScript or any other programming language. In this scenario, P represents th ...

Nested Promise.all within another Promise.all appears to terminate prematurely, triggering a warning indicating failure to return from a promise

I am utilizing this function to be invoked within another Promise.all. However, I consistently encounter a warning message: Caution: a promise was generated in a handler but was not returned from it. Additionally, the function deleteFutureAppointments() ap ...

What is the best way to extract the image url from a page in WordPress?

Is there a way to extract the image URL in WordPress dynamically for use as a reference in a script? When I use postimage(); it extracts this: <a href="address"> <img width="300" height="300" src="image.png" class="image" alt="" title="LINKING"/& ...

jQuery AJAX is seamlessly handling cross domain requests in Chrome and other browsers, however, it seems to be struggling in IE10 as it is not properly transmitting data. Additionally, in Internet

My web application requires sending data to an API hosted on a different domain. The API processes the received data and jQuery AJAX handles the response. This process works smoothly on Chrome and Firefox, but encounters issues on Internet Explorer. While ...

What is the reason for the continual influx of new users being added to the database?

I have a Node.JS and MongoDB console application where I've implemented adding users in one file and outputting all collection objects to the console in another file. When running the command - node scripts/get_all_users.js, both existing users are di ...

HTML/JavaScript - Ways to show text entered into an input field as HTML code

One dilemma I'm facing involves a textarea element on my website where users input HTML code. My goal is to showcase this entered HTML code in a different section of the webpage. How should I approach this challenge? The desired outcome is similar to ...

Harness the power of Bootstrap 5.3 color modes based on the user's browser

It has come to my attention that Bootstrap 5.3 introduces support for a customizable color scheme, allowing me to personalize various key features. Interestingly, the default dark theme now relies on the explicitly defined bs-theme data attribute rather t ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Can someone help clear up this confusion with CSS?

Why is image 6.png selected, when all the images are direct descendants of the div shape? Thank you for your assistance, it's greatly appreciated. As far as I know, it should select all the divs because they are all direct descendants of the div #shap ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Retrieving data stream from the redux store

My aim is to display a loading bar that reflects the progress of uploading a PSD file when a user initiates the upload process. For example: https://i.stack.imgur.com/fPKiT.gif I have set up an action to dispatch when the file begins uploading, and the ...

Saving a PHP form with multiple entries automatically and storing it in a mysqli database using Ajax

My form includes multiple tabs, each containing various items such as textboxes, radio buttons, and drop-down boxes. I need to save the content either after 15 seconds of idle time or when the user clicks on the submit button. All tab content will be saved ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

Establishing a Table of Disarray

I've hit a roadblock and I'm feeling confused about where to go next. Currently, I'm exploring the use of JavaScript to create tables for my data and display them in HTML. While I've successfully created the HTML table, I'm facing ...

Utilizing jQuery UI autocomplete with AJAX and JSON data sources

I've been facing an issue with the jQuery UI autocomplete feature, and despite extensive research, I have only managed to partially resolve it. The code below is what I'm currently using to make it work: $("#term").autocomplete({ source: fun ...

Tips for inserting a page break after every item in a loop in Visualforce when generating a PDF document

I need help with rendering a VF page as PDF. The VF page iterates over a list of account records using the repeat tag. I want to apply a page break for each element in the repeat tag. The code below is working, but it has an issue - it shows an empty PDF p ...

Stop the infiltration of emotions into your style

Utilizing the JsonForms React Component to dynamically generate an HTML form in my web application. The framework I am using handles all view rendering on the server side. To integrate this component, I compiled a small react component by running npm run b ...

Please note: With React 18, the use of ReactDOM.render is no longer supported. Instead, we recommend using create

I encountered an issue while attempting to link my React application with a MongoDB database. Here is the code snippet where the problem occurred: //index.js ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> &l ...