二维屏幕坐标转3维世界坐标对比:
PC端:
PC端常用的鼠标事件:click,mousemove等
mouse.x=(event.clientX/window.innerWidth)*2-1; mouse.y=-(event.clientY/window.innerHeight)*2+1;
移动端:
移动端在touch上一共有4个事件:touchstart 、touchmove 、touchend、 touchcancel。
一般来说,它们执行的顺序为 touchstart -> touchmove -> touchend -> touchcancel .
其中touchcancel一般情况下不会触发,
mouse.x=(event.touches[0].pageX/window.innerWidth)*2-1; mouse.y=-(event.touches[0].pageY/window.innerHeight)*2+1;
根据装置判断兼容性
var raycaster=new THREE.Raycaster(); var mouse=new THREE.Vector2(); function raycasterEvent(event){ event.preventDefault(); if(event.touches){ mouse.x=(event.touches[0].pageX/window.innerWidth)*2-1; mouse.y=-(event.touches[0].pageY/window.innerHeight)*2+1; }else{ mouse.x=(event.clientX/window.innerWidth)*2-1; mouse.y=-(event.clientY/window.innerHeight)*2+1; } raycaster.setFromCamera(mouse,camera); var intersect=raycaster.intersectObjects(scene.children,true); intersect[0].object.material.color.set(0xff0000); } window.addEventListener("click",raycasterEvent,false); //移动端必须使用移动端事件,否则无法检测 window.addEventListener("touchstart",raycasterEvent,false);