Combining Three.JS with object-oriented programming in JavaScript poses a challenge when attempting to pass a 3D JSON object to another class

Describing the issue in a single line proved to be difficult, so here's the situation at hand.

I'm embarking on a large Javascript project utilizing Three.js and aiming to grasp its OOP concepts.

1) I've created a 3D world Object
2) A base 3D_object class with child classes
3) In the snippet below, you'll notice option 1 and option 2 which should yield the same outcome, but for some reason they don't.
Any thoughts on why? The complete source code can be found in the snippet below.

(Make sure Three.js is included before the script and there is a 'resources/object.json' file present.)

Here is a GitHub link to the project; perhaps someone might find it helpful this way. (You may need to run it on a local Python server to bypass the cross-origin file loading issue in Chrome)

//create world
    var myWorld = new World(500,500);
    myWorld.AddWorldToPage();


    //load simple model in the world
    var cube = new Cube();
    myWorld.addToScene(cube);


    // load json model in the world
    //option 1
    // myWorld.addToSceneTemp();

    //option 2 OO (not working)
    var jsonObject = new Object_3D_JSON();
    function afterModelLoaded(){
        console.log("after loading is done");
        myWorld.addToScene(jsonObject);

    }
    jsonObject.loadModel(afterModelLoaded);


    myWorld.render();

// Inherits convenience method
//=====================================================================================================
function inheritsFrom(child, parent) {
  child.prototype = new parent();
  child.prototype.constructor = child;
}



// 3D Objects
//=====================================================================================================

// 3D object class
//=====================================================================================================
function Object_3DClass() {
    this._geometry = new THREE.BoxGeometry(1, 1, 1);
    this._material = new THREE.MeshBasicMaterial({
      color: 0xff00ff
    });
    this._mesh = new THREE.Mesh(this._geometry, this._material);
  }
  //Get 3D mesh
Object_3DClass.prototype.getMesh = function() {
  return this._mesh;
}

//Animate Object
Object_3DClass.prototype.animateFrame = function() {
  this._mesh.rotation.x += 0.01;
  this._mesh.rotation.y += 0.01;
}
Object_3DClass.prototype.setPosition = function(x, y, z) {
    this._mesh.position.set(x, y, z);
  }
  // END 3D object class
  //===================================================================================================

...


</html>

Answer №1

In order to properly pass a list of materials as a multimaterial in three.js, make the following changes:

Update this line:

self._mesh = new THREE.Mesh( geometry , materials );

to:

var materialSet = new THREE.MultiMaterial( materials );
self._mesh = new THREE.Mesh( geometry , materialSet );

Additionally, ensure you add a light to the scene when using JSON supplied materials to display lambert materials correctly (as lambert materials require lights whereas basic materials do not).

this._scene = new THREE.Scene();

var spotLight = new THREE.SpotLight( 0xffffff );
spotLight.position.set( 100, 1000, 100 );

spotLight.castShadow = true;

spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;

spotLight.shadow.camera.near = 500;
spotLight.shadow.camera.far = 4000;
spotLight.shadow.camera.fov = 30;

this._scene.add( spotLight );

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

MongoDB's implementation of prototypal inheritance within stored objects

Is it possible for MongoDB to save an object with another object as its 'prototype' in the same schema? For example: Assume we have this object in the database: { name : 'foo', lastName : 'bar', email : '<a hre ...

Cannot transmit unprocessed json data through retrofit

I've been struggling to send raw JSON using Retrofit 2 but for some reason, it's not working. I've experimented with JsonObject and map, but nothing seems to be working at all. It's strange because the request works fine on Postman. Her ...

Utilize the request module to fetch JSON data and then deliver the desired output

Utilizing the request module for handling HTTP requests in Node.js has proven to be quite handy. Here's a snippet of code showcasing its usage: module.exports.getToken = function(){ var token ; request(validLoginRequest, function(err,resp,b ...

Disabling the gl.BLEND Function in WebGL Fails to Function as Expected

Utilizing THREE.js with an enabled alpha canvas has been essential for incorporating my WebGL project onto another base. this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: false, alpha: true }); To establish the clear color, I&apos ...

Module is absent in JavaScript but present in TypeScript

As I delve into coding a vscode extension by following a tutorial, I encountered an issue with importing in my server.ts file. The directory structure looks like this: ...

Exploring variations in error handling for JavaScript promises in Node.js depending on whether the error is synchronous or asynchronous

Exploring the nuances of promise error handling for thrown errors and exceptions in the promise executor, particularly in comparison to reject, within a node.js context. Differences in handling between reject and throw/exceptions are evident. Some source ...

Set iframe scroll to match the height of the user's screen resolution

Can the height of an iframe scroll be adjusted to match the size of the screen (browser)? Essentially replacing the default browser scroll with the iframe scroll. Here's what I'm looking to achieve: Currently, my browser scroll is disabled: < ...

Eliminate the need for pressing the "tab" key on my website

I'm currently working on a horizontal web page layout and I'm looking for a way to disable the "tab" button functionality on my page. The issue arises because I have a contact form with textboxes located in the last div, and when users navigate u ...

Show a preview of an image in an HTML document

How can I display an image after uploading it? I attempted to use the following code, but it didn't work: onFileSuccess: function(file, response) { var json = new Hash(JSON.decode(response, true) || {}); if (json.get('status& ...

Discovering the central point within an SVG path

I am currently working with a path that is part of a group and using Jquery to locate the specific path. My goal is to find the midpoint of that path. I came across an example here. However, when attempting to use .getTotalLength(); or .getPointAtLength(), ...

Activate all chosen CSS circles

I'm currently working on creating a progress bar using CSS circles. The idea is that when you click on each circle in sequence (1, 2, 3), all three circles and the line connecting them will fill up with red color. If you then go back (3, 2, 1), the co ...

Unable to obtain the vertices of the extremities due to the absence of labels on AxisHelper

My goal is to add labels on AxisHelper in Three.js that rotate along with it. I came across a helpful code snippet from this source: // Axes axes2 = new THREE.AxisHelper(70); // Axes labels addLabelAxes(); // Add axes to zoomScene zoomScene.add(axes2); ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

Unable to verify the provided resource: Mailchimp

Welcome everyone to my first question posted on StackOverflow. I have tried my best to provide all the necessary details regarding the issue in order to seek assistance. If you require additional information, feel free to ask. To give a brief overview, I ...

Steps for implementing a click-event in a modal

Hi there, I'm fairly new to JavaScript and I've been working on implementing a feature where a Bootstrap modal opens when a button is clicked (the button's ID is set dynamically from a database). If the user clicks "Yes" in the modal, it sho ...

Having issues with Google Maps API v3 not loading properly

I'm encountering an issue with initializing a map upon window load. While the problem is similar to this question, I am not utilizing jQuery to create the map, rendering the solution provided there inapplicable to my situation. Here's my code sni ...

Issue with Symfony2 JMS Serializer JSON_ constant error

An unexpected error occurred while trying to install a project on the production server. The PHP Fatal error states: 'Uncaught exception 'JMS\Serializer\Exception\InvalidArgumentException' with message 'Expected either an ...

Having a problem with Node.js and async.eachSeries? Want to figure out how to configure the callback function to generate a JSON file for each element in an array of

Currently, I am utilizing async.eachSeries to repeatedly call a function that generates an array called pointsForFormating. Each time this function is called, I format the pointsForFormating array and store the result in another array named pointsFormate ...

Converting Json string to a Set of objects in Java

Despite searching for two days, I haven't been able to find a solution to my problem with parsing a json string. Here is the json string: [ { "firstName": "dan", "lastName": "cohen", "email&qu ...

Prevent computed observables from being included in server data by using KnockoutJS

While working on this project, I came across a helpful section in that discusses "Determining if a property is a computed observable." In order to achieve this, I utilized the isComputed function to validate whether a property is indeed a computed observa ...