Reputation:
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 );
// });
Upvotes: 1
Views: 2109
Reputation:
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);
});
}
Upvotes: 2
Reputation: 374
loading an obj replaces making the new THREE.boxGeometry() part not new THREE.Mesh(). this code doesn't seem to be without errors.
Anyway, take a look at the code below, notice that inside loader.load I changed the second argument from object to geometry and uncommented the mesh making:
var loader = new THREE.OBJLoader();
loader.load('static/obj/cube.obj', function(geometry) {
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 );
});
now OBJLoader gets the geometry, and uses it to make a mesh. It makes more sense doesn't it?
Upvotes: 0