0

for my internship in need to make an aplication with three.js what needs to be in a container on a page but it needs an onclick function on the objects. the problem is i cannot find annything on raycasting only in a container and clicking now will not get objects i need

application

onMouseDown(event) {
    let s = this;

    // calculate mouse position in normalized device coordinates
    // (-1 to +1) for both components
    s.mouse.x = ( event.clientX / s.renderer.domElement.clientWidth ) * 2 - 1;
    s.mouse.y = - ( event.clientY / s.renderer.domElement.clientHeight ) * 2 + 1;


    s.intersects = s.raycaster.intersectObjects(s.blocks, true);
    for ( var i = 0; i < s.intersects.length;){

        s.intersects[ i ].object.material.color.set( 0xff0000 );
        console.log(i)
        console.log(s.getScene().children)
        console.log(s.intersects)
        console.log("test 123")

    } 
    if (s.intersects == 0){
        console.log(s.mouse.x)
        console.log(s.mouse.y)
    }

}

edit: it is not the same as Detect clicked object in THREE.js he is not working in a container. plus he has a little problem with the margins for me everywhere i click on the screen it does not detect what i need and i need it to be working only on the container not the whole webpage plus there help is outdated and is not working annymore

C4rdZ
  • 37
  • 7
  • Possible duplicate of [Detect clicked object in THREE.js](https://stackoverflow.com/questions/7956442/detect-clicked-object-in-three-js) – Jeppe Feb 04 '19 at 09:02
  • did you leave out some of the code? Because it looks like you are not setting up the raycaster with your mouse-coordinates. – Martin Schuhfuß Feb 04 '19 at 10:21
  • i left out some code yeah i got my main problem fixed but now running into a new problem and that is that the click will not see the object\ – C4rdZ Feb 04 '19 at 11:01

1 Answers1

1

If you are working with a canvas that is not at the top-left corner of the page, you need one more step to get to the normalized device coordinates. Note that the NDC in WebGL are relative to the canvas drawing-area, not the screen or document ([-1,-1] and [1,1] are the bottom-left and top-right corners of the canvas).

Ideally, you'd use ev.offsetX/ev.offsetY, but browser-support for that isn't there yet. Instead, you can do it like this:

const {top, left, width, height} = renderer.domElement.getBoundingClientRect();

mouse.x = -1 + 2 * (ev.clientX - left) / width;
mouse.y = 1 - 2 * (ev.clientY - top) / height;

See here for a working example: https://codepen.io/usefulthink/pen/PVjeJr

Another option is to statically compute the offset-position and size of the canvas on the page and compute the final values based on ev.pageX/ev.pageY. This has the benefit of being a bit more stable (as it is not scrolling-dependent) and would allow to cache the top/left/width/height values.

Martin Schuhfuß
  • 6,814
  • 1
  • 36
  • 44