Utilize a unique mesh instead of a generated one within three.js

Recently, I stumbled upon the fascinating world of three.js and I must say, it's quite amazing. After downloading some examples, I delved into exploring them.

As someone who is new to coding in JavaScript, I find myself in need of assistance with modifying one of the example files (misc_controls_trackball.html). My query pertains to replacing the generated geometry (mesh.position.x = ( Math.random() - 0.5 ) ...) with a pre-made mesh (perhaps from software like 3 studio max). Is this possible?

I believe the following section of the code is responsible for generating the mesh:

            // world

            scene = new THREE.Scene();
            scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );

            var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 );
            var material =  new THREE.MeshLambertMaterial( { color:0xffffff, shading: THREE.FlatShading } );

            for (var i = 0; i < 500; i++) {

                var mesh = new THREE.Mesh(geometry, material);
                mesh.position.x = (Math.random() - 0.5) * 1000;
                mesh.position.y = (Math.random() - 0.5) * 1000;
                mesh.position.z = (Math.random() - 0.5) * 1000;
                mesh.updateMatrix();
                mesh.matrixAutoUpdate = false;
                scene.add(mesh);

            }

How can this code be modified to allow me to import an external mesh (in .3ds, .obj, .dae format, etc.)?

Thank you in advance for your assistance.

You can access the misc_controls_trackball.html example file along with the "js" folder here.

Answer №1

Have you given this a try?

This is an example for Collada files, but the same concept applies to other formats, just utilizing a different loader.

var loader = new THREE.ColladaLoader();

// Depending on your model creation method, you may need to
loader.options.convertUpAxis = true;

// Then proceed to load it:
loader.load( './models/collada/monster/monster.dae', function ( collada ) {
    // All of this will happen asynchronously

    dae = collada.scene;

    // Before displaying it, you can adjust it as needed
    dae.scale.x = dae.scale.y = dae.scale.z = 0.002;
    dae.updateMatrix();

    scene.add(dae);
    // Your model will be loaded in the next frame.
} );

UPDATE, additional information

Firstly, you require the links to the appropriate libraries, including the ColladaLoader

    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r69/three.js"></script>
    <script src="js/loaders/ColladaLoader.js"></script>

Various issues needed addressing in the code. - The scene object was absent
- The model was loaded, but needed to be scaled up slightly
- The animate function lacked a call to render(), resulting in no animation
- The fog statement was faulty... It would be beneficial to focus on the fundamentals first...

        function init() {

            // Establish your scene first
            scene = new THREE.Scene();

            camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
            camera.position.z = 500;

            controls = new THREE.TrackballControls( camera );

            controls.rotateSpeed = 1.0;
            controls.zoomSpeed = 1.2;
            controls.panSpeed = 0.8;

            controls.noZoom = false;
            controls.noPan = false;

            controls.staticMoving = true;
            controls.dynamicDampingFactor = 0.3;

            controls.keys = [ 65, 83, 68 ];

            controls.addEventListener( 'change', render );

            // world

            var loader = new THREE.ColladaLoader();

            // Depending on how you created your model, you may need to
            loader.options.convertUpAxis = true;

            // Then load it:
            //loader.load( './models/collada/monster/monster.dae', function ( collada ) {
            loader.load( 'models/monster.dae', function ( collada ) {
                // All this will happen asynchronously

                dae = collada.scene;

                // Give it a decent scale
                dae.scale.x = dae.scale.y = dae.scale.z = 1;
                dae.updateMatrix();

                scene.add(dae);
                // At the next frame, you`ll have your model loaded.
            } );


            // lights

            light = new THREE.DirectionalLight( 0xffffff );
            light.position.set( 1, 1, 1 );
            scene.add( light );

            light = new THREE.DirectionalLight( 0x002288 );
            light.position.set( -1, -1, -1 );
            scene.add( light );

            light = new THREE.AmbientLight( 0x222222 );
            scene.add( light );


            // renderer

            renderer = new THREE.WebGLRenderer( { antialias: false } );
            //renderer.setClearColor( scene.fog.color, 1 );
            renderer.setSize( window.innerWidth, window.innerHeight );

            container = document.getElementById( 'container' );
            container.appendChild( renderer.domElement );

            stats = new Stats();
            stats.domElement.style.position = 'absolute';
            stats.domElement.style.top = '0px';
            stats.domElement.style.zIndex = 100;
            container.appendChild( stats.domElement );

            //

            window.addEventListener( 'resize', onWindowResize, false );

            // The following is not necessary at this stage, as you`ll call it
            // from animate later down (if you want to do an animation, of course,
            // which I guess you do)
            render();

        }

The animate function should be structured as follows

        function animate() {

            requestAnimationFrame( animate );
            controls.update();
            render();

        }

Hopefully, this information proves helpful! :)

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

Tips for connecting elements at the same index

.buttons, .weChangeColor { width: 50%; height: 100%; float: left; } .weChangeColor p { background: red; border: 1px solid; } .toggleColor { background: green; } <div class="buttons"> <p><a href="#">FirstLink</a></ ...

Ensure to update the canvas prior to the function finishing

Is there a way to update the canvas element while inside a JavaScript function without waiting for the function to return? It can be frustrating when you want to keep the function running but also need to update the canvas element in real time. ...

Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyu ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Extracting a particular element from a sophisticated auto-complete DOM structure by drilling down into the $scope

After spending a significant amount of time trying to solve this problem, I find myself at a dead end. The simplicity of using jQuery makes me reconsider Angular, but perhaps my approach is flawed. In this scenario, the DOM structure looks like this: < ...

Moving a Ball Back and Forth Using Three.js

I’m looking to create a continuous motion for a Ball in Three.js, where it moves to the right, returns to its starting position, and then repeats the sequence. var geometry = new THREE.SphereGeometry( 5, 32, 32); var material = new THREE.MeshPhongMateri ...

Issue encountered when implementing promise and await within a Vue method

I've implemented a function in the mounted() hook to fetch files from my Dropbox account using a promise. Once the promise is resolved successfully, I iterate through all the files and execute another promise function to retrieve additional informatio ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Creating an array of objects by utilizing another array - the process explained

I am looking to create a new array by pushing objects after checking the values in an existing array. Here are the conditions: var ar=['aa','cc','po'] var arr =[{name:"po"},{name:'aa'},{name:'cc'}]; Desi ...

Fulfill the promise to retrieve the value contained within

Is there a way to use TypeScript to call the Wikipedia API for retrieving a random page title and save it in a variable for later use? I am struggling with resolving promises as I keep getting ZoneAwarePromise returned. I'm new to both promises and Ty ...

What is the best method for encrypting a file using node.js?

I am in the process of finding a way to encrypt various types of files like txt, mp3, or any other file in node.js while utilizing socket.io. My goal is to develop an application that can securely send files to another client, so I wish to encrypt the file ...

How can I substitute a specific capture group instead of the entire match using a regular expression?

I'm struggling with the following code snippet: let x = "the *quick* brown fox"; let y = x.replace(/[^\\](\*)(.*)(\*)/g, "<strong>$2</strong>"); console.log(y); This piece of code replaces *quick* with <strong& ...

Guide on programmatically changing the position of a shape in SVG

Check out this tutorial on how to make SVG elements draggable using JQuery and Jquery-svg. The accepted answer provides an implementation for moving a circle by changing the cx and cy attributes. But how can I achieve drag-and-drop functionality for a pol ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

"Converting Text from a Streamed XML-Like File into CSV: A Step-by-Step Guide

I have log files that contain C++ namespace artifacts (indicated by the double colons ::) and XML content embedded within them. After loading and displaying the logs in a browser application, the content has been separated from the Unix timestamps like so: ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

preventing users from selecting past dates on Full Calendar Plugin

Is there a way to disable the previous month button on the full calendar? Currently it is April. When I click on the previous button, the calendar shows March instead of disabling. How can this be prevented? http://jsfiddle.net/6enYL/ $(document).ready( ...

Is there a more efficient method than creating a separate variable for the navbar on each individual page where it is being utilized?

Apologies for the unclear title, I struggled to find the right wording and decided it would be easier to illustrate with code. Let's assume I have the following routes: router.get('/chest', (req, res)=>res.render('muscles/chest/chest ...

Is there a way to execute code after completion of all threads?

I've developed a multi-threaded web crawler that downloads a website and stores it in a database, however, this process takes around 4 minutes. In an attempt to speed up the crawling process, I implemented the node.js cluster module. Yet, I'm fac ...