Threejs issue with raycaster intersection

独自空忆成欢 提交于 2020-01-05 12:33:06

问题


I wrote a code to intersect some object and worked fine until I put canvas with other div in html document. Now there are no intersection on the object. In this Live example:http://www.felpone.netsons.org/web-threejs/index1.html if you select on the right top the button cross and try to move the shape you can't. You can move shape if you put your mouse a little bit at right of the shape. So the intersection is completely wrong. I tried some solutions posted on stackoverflow but doesn't work. Can anyone help me to understand please? I am desperate.

In this other live example you can see how it should work : http://www.felpone.netsons.org/web-threejs/. I tried with other solutions written on Stackoverflow but without result.

Maybe can depend by mouse coordinates:

mouse2D.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / renderer.domElement.width ) * 2 - 1;
mouse2D.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / renderer.domElement.height ) * 2 + 1;

Here you can see the javascript code : http://www.felpone.netsons.org/web-threejs/stereos.js

Maybe can depend by:

I noticed that there are two differents dimension for canvas as you can see in this screenshot:


回答1:


event.clientX is relative to the browser window. You want the offset relative to the canvas. So you have to select the offset for each element containing the canvas.

This is some nice clean code that will do what you want: https://stackoverflow.com/a/5932203/2195930

I use this code everytime I deal with a mouse over a canvas.

If you had a simpler test case, I'd try to mock up the whole solution for you.




回答2:


Try to change a code as follows:

var x = event.offsetX == undefined ? event.layerX : event.offsetX;
var y = event.offsetY == undefined ? event.layerY : event.offsetY;

mouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;
mouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;



回答3:


In your DOM, canvas appears as

<canvas width="1139" height="975"></canvas>

That is from where your script is taking height and width.

However, the real dimensions of the canvas come from the

width: 100%;
height: 100%;

in your CSS.

I would remove one of them, so that the scripting can take the correct value without problems



来源:https://stackoverflow.com/questions/27923388/threejs-issue-with-raycaster-intersection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!