Search code examples
three.jsdraggable

Drag a loaded object with threejs?


I've been trying to get a loaded object to be draggable in threejs. The first block of code below (which is only a snippet) displays a cube and I can rotate the view, but not the cube itself.

The second block of code creates a box that is draggable, but I want to be able to do more than just drag boxes. Like maybe drag a teapot! Thus the desire to drag a loaded object.

Why can I move the box when I create it with threejs, but not when I load it? How do I fix this?

The code derived from: http://threejs.org/examples/webgl_interactive_draggablecubes.html

// var geometry = new THREE.BoxGeometry( 40, 40, 40 );

var loader = new THREE.OBJLoader();
loader.load('static/obj/cube.obj', function(object) {

    // var object = new THREE.Mesh( geometry, 
                    new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) );

    object.position.x = Math.random() * 100 - 50;
    object.position.y = Math.random() * 60 - 30;
    object.position.z = Math.random() * 80 - 40;

    scene.add( object );

    objects.push( object );

});

var geometry = new THREE.BoxGeometry( 40, 40, 40 );

// var loader = new THREE.OBJLoader();
// loader.load('static/obj/cube.obj', function(object) {

var object = new THREE.Mesh( geometry, 
             new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) );

object.position.x = Math.random() * 100 - 50;
object.position.y = Math.random() * 60 - 30;
object.position.z = Math.random() * 80 - 40;

scene.add( object );

objects.push( object );

// });

Solution

  • The code below works and allows me to drag the object because the way I drag objects requires a mesh as a child of the scene.

    if (objfile) {
    
            var texture = new THREE.Texture();
            var img = new THREE.ImageLoader();
            img.load('static/material/red.png', function(image) {
                texture.image = image;
                texture.needsUpdate = true;
            });
    
            var objModel = new THREE.OBJLoader();
            var mesh;
    
            objModel.load('static/obj/' + objfile + '.obj', function(object) {
                object.traverse(function(child) {
                    if (child instanceof THREE.Mesh) {
                        child.material.map = texture;
                        mesh = child;
                    }
                });
    
                scene.add(mesh);
            });
        }