What is the best way to switch from using the three.js JSONLoader to the ObjectLoader?

I successfully loaded multiple files using the code below for three.js JSONLoader:

<!DOCTYPE html>
<html>
  <head>
    <title>Rotating Sphere</title>
    <meta charset="utf-8">
    
    <!-- https://cdnjs.com/libraries/three.js -->
    <script src="http://www.amdesigngroup.com/clients/AM_6292_Learning/js/three.min.js"></script>
    <script src="http://www.amdesigngroup.com/clients/AM_6292_Learning/js/OrbitControls.js"></script>
    <!-- Tween.js: https://cdnjs.com/libraries/tween.js/ -->
    <script src="http://www.amdesigngroup.com/clients/AM_6292_Learning/js/Tween.js"></script>
  </head>
  <body style="margin: 0; background-color:#6cdbf5;">
    <div class="canvas-wrapper">
      <canvas id="mycanvas">

      </canvas>
    </div>
    
    
    

      // Code here

      
    </script>
  </body>
</html>

Unfortunately, I encountered issues with trying to load two models using the ObjectLoader. It seems like there are errors related to GeometryUtils.center and a.center being undefined. How can I resolve these errors and why are they occurring?

It appears that JSONLoader and ObjectLoader operate differently, leading to compatibility issues in my code. Despite attempting various fixes, I couldn't find helpful information online or in the documentation. Any guidance on rectifying these errors would be greatly appreciated!

Thank you for your assistance!!!

NOTE: Apologies for the messy code - I understand it's not optimized, but currently, functionality is the primary focus. Cleanup will be done later!

Answer №1

Found the solution here:

var loader = new ObjectLoader();
loader.load('scene.js', function(object) {
    scene.add(object); // add the object to the scene
});

The issue was not receiving the object as a function argument and failing to include it in the scene. I was attempting to use mesh/geometry instead of the object loader. The provided code below resolved the issue:

<!DOCTYPE html>
<html>
  <head>
    <title>Rotating Sphere</title>
    <meta charset="utf-8">
    
    <!-- https://cdnjs.com/libraries/three.js -->
    <script src="js/three.min.js"></script>
    <script src="js/OrbitControls.js"></script>
    <!-- Tween.js: https://cdnjs.com/libraries/tween.js/ -->
    <script src="js/Tween.js"></script>
  </head>
  <body style="margin: 0; background-color:#6cdbf5;">
    <div class="canvas-wrapper">
      <canvas id="mycanvas">

      </canvas>
    </div>
    
    
    <script>

      function createObject(filePath) {
        var canvas = null,
            scene = null,
            camera = null,
            renderer = null,
            mesh = null,
            mesh2 = null,
            object = null;

        init();
        run();

        function init() {

          canvas = document.getElementById( "mycanvas" );
          scene = new THREE.Scene();
          var WIDTH = window.innerWidth,
              HEIGHT = window.innerHeight;

          renderer = new THREE.WebGLRenderer({antialias:true, alpha:true, canvas:canvas});
          renderer.setSize(WIDTH, HEIGHT);
          document.body.appendChild(renderer.domElement);

          camera = new THREE.PerspectiveCamera(45, WIDTH / HEIGHT, 0.1, 20000);
          camera.position.set(0,6,0);
          camera.lookAt(scene.position);
          scene.add(camera);

          window.addEventListener('resize', function() {
            var WIDTH = window.innerWidth,
                HEIGHT = window.innerHeight;
            renderer.setSize(WIDTH, HEIGHT);
            camera.aspect = WIDTH / HEIGHT;
            camera.updateProjectionMatrix();
          });

          var light = new THREE.PointLight(0xffffff);
          light.position.set(0,0,-100);
          scene.add(light);

          var loader = new THREE.ObjectLoader();
          loader.load( filePath, function(object, materials){
            object.rotation.x = - (Math.PI / 2);
            object.rotation.y = Math.PI;
            scene.add(object);
          });

          var loader2 = new THREE.ObjectLoader();
          loader2.load( "models/Platform/Platform.json", function(object, materials){
            object.rotation.x = - (Math.PI / 2);
            object.rotation.y = Math.PI;
            object.scale.set(.025, .025, .025);
            object.position.set(0, 1, .4);
            scene.add(object);
          });

          controls = new THREE.OrbitControls(camera, renderer.domElement);

        }
        
        function animate(mesh) {
          var tween = new TWEEN.Tween(mesh.rotation)
            .to({ z: "-" + Math.PI/2}, 2500)
            .onComplete(function() {
                if (Math.abs(mesh.rotation.z)>=2*Math.PI) {
                    mesh.rotation.y = mesh.rotation.z % (2*Math.PI);
                }
            })
            .start();
          tween.repeat(Infinity)
        }

        function run() {

          requestAnimationFrame(run);
          TWEEN.update();

          renderer.render(scene, camera);
          controls.update();
        }
      
      }
      
      createObject("models/ConstructionManA_2/ConstructionManA_2.json");

    </script>
  </body>
</html>

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

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

Having multiple upload forms on a single page with PHP, AJAX, and jQuery is not functioning as expected

I'm on the hunt for a jQuery-AJAX image uploader that supports multiple instances of the form on a single page. Do you have any recommendations? Here's my scenario: I have a front-end page where users can update their profiles. Upon loading the ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

Scrolling presentation with dynamic animations

Does anyone have any suggestions for creating a scrolling effect similar to the one on this website? I want to implement a scroll effect where each presentation page is revealed one by one when the user scrolls using their mouse wheel, encouraging them to ...

How can I obtain the current state of HTML checkboxes from a local JSON file?

I have an HTML table with checkboxes, and I want to save the state of each checkbox in a local .JSON file instead of using localStorage. When the page reloads, I want it to automatically load the saved JSON file to retrieve the previously configured checkb ...

Having trouble getting AngularJS ngCloak to function properly?

My post category page is supposed to display a message if there are no posts. However, the HTML appears briefly when the page loads and then hides. I thought using ngCloak would solve this issue, but it doesn't seem to be working for me. Here's t ...

Using v-bind:class in Vue.js does not successfully assign a value in the method

Why is the width of my div not changing when I try to bind it to a data attribute that ranges from 0 to 100? <div class="bar" :style="{ width: percentage + '%' }"></div> <script> export default { name: 'app&ap ...

Loading texts with the same color code via ajax will reveal there are differences among them

I am currently designing a webshop with green as the primary color scheme. Everything is functioning perfectly, but I have noticed that the text within an ajax loaded div appears brighter than it should be. The text that loads traditionally is noticeably d ...

Effortless Ways to Automatically Accept SSL Certificates in Chrome

It has been quite some time that I have been attempting to find a way to automatically accept SSL certificates. Unfortunately, I haven't had any success yet. The scenario is this: I am working on selenium tests and every time I run the test on Chrome, ...

There was an error due to a TypeError: The 'page' property cannot be read because it is undefined

Can anyone assist me with an Angular issue I'm facing? I've been working on integrating server-side pagination, but no matter how many times I revise my code, I keep encountering the same error message: ERROR TypeError: Cannot read properties o ...

The AngularJS ng-repeat filter {visible: true} does not respond to changes in properties

var myApp = angular.module('myApp', ['infinite-scroll']); myApp.controller('DemoController', function($scope, $timeout, $rootElement) { $scope.$rootElement = $rootElement; $scope.$timeout= $timeout; $scope.init = ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Firebug version 2.0.1 has been triggered to break on previous breakpoints

Despite adding and removing breakpoints, Firebug continues to stop at the old breakpoints upon refreshing the page. I attempted solutions such as resetting all Firebug options and deleting the breakpoints.json file, but they have not resolved the issue. ...

Error: Trying to add an element to an undefined variable (d3 force layout)

I've been racking my brain trying to solve this error I keep encountering while working with a force layout. The problem arose when I switched to reading nodes from a JSON file. When I comment out certain lines, the error disappears. But if I leave th ...

Transferring a JavaScript Value to a PHP Variable (Under Certain Constraints)

Although I have reviewed existing questions and answers related to this issue, I found that the solutions provided do not suit my specific situation. Discussing the differences between client-side JavaScript and server-side PHP, two common solutions are: ...

Retrieve the data attribute from a specific dropdown menu using jQuery

Here is the code snippet I am currently working with: $('.tmp-class').change(function() { $('.tmp-class option:selected').each(function() { console.log($('.tmp-class').data('type')); }) ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

What could be the reason for the appearance of this error message: 'Illegal arguments: undefined, string'?

Currently, I am in the process of developing a node.js application where I have created a backend API specifically for user registration. However, when testing it using Postman, I encountered an error message stating 'Illegal arguments: undefined, str ...

Enabling communication between JavaScript and PHP and vice versa

I am currently working on developing a Firefox plug-in with the purpose of gathering all the domains from the links located on the current site and showcasing their respective IP addresses. In order to achieve this, I have written JavaScript code that incl ...