1

I have a unique situation where I'd like to actually be able to simulate a click onto an object. For example, a UI provides a way to pick out a certain element inside of the scene via scene.getObjectByName(objectName, true) and I'd like to be able to click this object.

Obviously, I could expose the functionality of what the real click would do, but in these situations, I need to actually drive a click on the screen via JavaScript (e.g. $canvas.trigger($.Event('click', { clientX: 10, clientY: 20 }))).

What are the best techniques for doing this. I'd imagine I would have to convert the object's position to screen (X, Y) and simply trigger a click at those coordinates? But this would require precise coordinates for a click and I'm not sure how to get that from a mesh.

gman
  • 100,619
  • 31
  • 269
  • 393
Detuned
  • 3,652
  • 4
  • 27
  • 54

1 Answers1

0

This is a duplicate, i'm sure.

Here's a way anyways:

fetchRayCastTop = function (event, arr, camera, renderer) {
    var testSet = arr;
    if (this.raycaster === false) {
            this.raycaster = new THREE.Raycaster();
    }
    var mouse = new THREE.Vector2();
    mouse.x = event.offsetX / renderer.domElement.width * 2 - 1;
    mouse.y = -(event.offsetY / renderer.domElement.height) * 2 + 1;
    this.raycaster.setFromCamera(mouse, camera);
    var intersects = this.raycaster.intersectObjects(testSet, true);
    object = undefined;
    if (intersects.length > 0) {
            object = intersects[0];
    }
    return object;
};

Usage that toggles a mesh color:

var alistOfObjectsYouWantMouseeventsFor = [list of object3d objects here.];

element.addEventListener("click", function(e){
    picked = fetchRayCastTop(e, alistOfObjectsYouWantMouseeventsFor, yourCamera, yourRenderer);
    var mat = picked.object.material;
    if(mat != undefined){
      if(mat.length == undefined){
        mat = [mat];
      }
      for(var i=0; i<mat.length; i++){
        if(mat[i].cachedColor != undefined){
            mat[i].color.copy(mat[i].cachedColor);
            delete mat[i].cachedColor;
        }else{
          mat[i].cachedColor = new THREE.Color().copy(mat[i].color);
          mat[i].color.setHex(0xFF0000);
          mat[i].side = THREE.DoubleSide;
        }
     }
});
Radio
  • 2,810
  • 1
  • 21
  • 43