Alan
Alan

Reputation: 2086

Three.JS Ray_tracing intersect wrong while embedded on HTML page

I have Three.JS running in a div on a webpage that is offset using bootstrap by x:200,y:150 to make room for a header and navigation area as you can see here: https://jsfiddle.net/cx47458f/3/

The issue I am running into is using the ray_tracing / Vector3() function where it isn't reading the proper click location. Using the following code:

        function ray_tracing(e,objects){
            var uv  = new THREE.Vector3();
            if (e.offsetX){  //chrome,ie,safari
                uv.x = e.offsetX+(navarea.innerWidth()/2)+7;
                uv.y = e.offsetY+(viewer.innerHeight()/5)-70;
            }else{ //firefox
                uv.x = e.layerX;
                uv.y = e.layerY;    
            }

            uv.x = 2*(uv.x/window.innerWidth) - 1;
            uv.y = 1 - 2 * (uv.y/window.innerHeight);
            var cam = camera.clone();
            var raycaster = new THREE.Raycaster();

            raycaster.setFromCamera( uv, cam );
            return raycaster.intersectObjects( objects );

        }   

I was able to get it to be almost perfect initially, as long as the green ball is in the middle of the viewing area. However, the farther it gets from the middle, the farther away the clickable intersect point becomes. You do need to expand the JSFiddle preview area to show the left navigation, otherwise it doesn't work at all. Since it isn't full screen, how do I deal with this to prevent the intersect point from drifting?

Is there a way to have this not in an iframe, and still get it to be responsive in sizing, while keeping the functionality? Ultimately I would like to be able to have some buttons on the navigation to add items to the scene or change scene entirely which is why I was avoiding the iframe.

Upvotes: 0

Views: 126

Answers (1)

Alan
Alan

Reputation: 2086

The solution ended up being this in the onDocumentMouseMove(event):

  var canvasWidth = canvas.innerWidth();
  var canvasHeight = canvas.innerHeight();
  var mouseOffset = canvas.offset();
  mouse.x = ((event.clientX - mouseOffset.left) / canvasWidth) * 2 - 1;
  mouse.y = - ((event.clientY - mouseOffset.top) / canvasHeight) * 2 + 1;

This morning I also found this example while looking for TextGeometry examples. http://threejs.org/examples/#webgl_multiple_elements_text

Upvotes: 0

Related Questions