threejs通过射线Ray获取指定的点

时间:2022-07-05 04:01:52

例:获取cube方向上的面的中点坐标(该cube默认方向为(0,1,0))

(中心点向cube quaternion 方向上发射射线,与正前方的面相交的点即为目标点;

由于ray只支持box和face,所以需要先生成与cube相同的box)

let center = cube.position.clone(),
  quaternion = cube.quaternion.clone(); //获取cube的长宽高
cube.geometry.computeBoundingBox();
let size = this.cube.geometry.boundingBox.getSize();
let scale = this.cube.scale;
let scaleSize = new THREE.Vector3(size.x * scale.x, size.y * scale.y, size.z * scale.z); //在坐标原点位置生成box,方便ray射线操作.该box长宽高与cube一致,只是quaternion不同
let box = new THREE.Box3()
    .setFromCenterAndSize(new THREE.Vector3(0, 0, 0), scaleSize); //在坐标原点位置生成box和ray,得到目标点,再通过quaterion变换到目标位置
let ray = new THREE.Ray(new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 1, 0));
let intersect = ray.intersectBox(box); //该点由于射线原点在(0,0,0),所以applyQuaternion只起到旋转作用
let rotatedPoint = intersect.applyQuaternion(quaternion)
//最后位移center 的向量
let point=rotatedPoint.add(center)