threejs 点击模型拾取,页面有偏移导致拾取不准

  • 方式一:适合页面无偏移的情况
let mouse = new THREE.Vector2(
    (event.clientX / this.dom.offsetWidth) * 2 - 1,
    -(event.clientY / this.dom.offsetHeight) * 2 + 1
);
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, this.camera);
let intersects = raycaster.intersectObject(object.model, true);
  • 方式二:页面有偏移
let mouse = new THREE.Vector2(
    ((event.clientX - this.dom.getBoundingClientRect().left) / this.dom.offsetWidth) * 2 - 1,
    -((event.clientY - this.dom.getBoundingClientRect().top) / this.dom.offsetHeight) * 2 + 1
);
 
let standardVector = new THREE.Vector3(mouse.x, mouse.y, 1);// 标准设备坐标
let worldVector = standardVector.unproject(this.camera); // 标准设备坐标转世界坐标
let ray = worldVector.sub(this.camera.position).normalize();// 射线投射方向单位向量(worldVector坐标减相机位置坐标)
let raycaster = new THREE.Raycaster(this.camera.position, ray);
let intersects = raycaster.intersectObject(object.model, true);
  • 方式三:页面有偏移
let mouse = new THREE.Vector2(
    ((event.clientX - this.dom.getBoundingClientRect().left) / this.dom.offsetWidth) * 2 - 1,
    -((event.clientY - this.dom.getBoundingClientRect().top) / this.dom.offsetHeight) * 2 + 1
);
 
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, this.camera);
let intersects = raycaster.intersectObject(object.model, true);

.clientX .clientY是以设备左上角为坐标原点,单位px。 .offsetX .offsetY是以canvas画布左上角为坐标原点,单位px

posted @ 2024-11-22 11:27  ZerlinM  阅读(39)  评论(0编辑  收藏  举报