Jack
Jack

Reputation: 387

Detect click on mesh of 3DObject

I have a model loaded in from .obj and .mtl I want the user the be able to click on specific parts of the model and, for example, change their colour. i.e click on a door of the car and be able to change the colour of that door mesh.

Here's my model load code, if it's needed.

var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setPath('Models/Aventador/');
    mtlLoader.load('Avent.mtl', function (materials) {
        materials.preload();
        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials(materials);
        objLoader.setPath('Models/Aventador/');
        objLoader.load('Avent.obj', function (object) {
            object.position.y = 0;          
            scene.add(object);
        }, onProgress, onError);
    });

EDIT: I now have the following code, which gives no errors and prints out 'mouseup' to the console as expected but does not print out any intersections as expected, any ideas what's wrong?

var mouse = new THREE.Vector2();
function onDocumentMouseUp(event) {
    console.log("mouseUp")
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
    var raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(mouse, camera);
    var intersects = raycaster.intersectObjects(scene.children);
    for (var i = 0; i < intersects.length; i++) {
        console.log(intersects[i]);
        intersects[i].object.material.color.set(0x0000ff);
    }
}

EDIT 2: helper arrows

Upvotes: 1

Views: 1496

Answers (1)

Hectate
Hectate

Reputation: 212

So for the clicking part, you'll want to raycast to the model from the mouse's position. The link below should give you enough information to get started:

Raycaster

The raycast should tell you what object you hit, and then you can remember that object for use (changing color properties, for example).

In answer to your other question, the objects is similar to the scene.children seen in the link above. You could also pass just the mesh to it and see if it hits that (instead of say, a light or a flat plane that you have the car sitting on for a surface).

Edit: Because it was an Obj, we figured out in chat that we needed to follow along with this answer and enable recursion on the raycast to get it to detect the portions of the model required.

Upvotes: 1

Related Questions