Skip to content

Q4: 什么是射线投射?在 VR 看房项目中如何应用?

口头回答

面试官您好,射线投射(Raycasting)是3D图形学中的一项重要技术,它的基本原理是从一个点(通常是相机位置)沿着特定方向发射一条虚拟射线,然后检测这条射线与场景中哪些3D物体相交。

射线投射的核心概念:

  1. 射线定义:由起点和方向向量定义的无限延伸的直线
  2. 相交检测:计算射线与3D物体(如网格、精灵等)的交点
  3. 距离排序:按照交点到射线起点的距离进行排序
  4. 交互响应:根据相交结果执行相应的交互逻辑

在我们的VR看房项目中,射线投射主要应用于两个核心场景:

  1. 导航点击交互:当用户点击房间导航图标时,通过射线投射检测点击的是哪个导航精灵,然后执行相应的房间切换动画。

  2. 信息点悬停检测:当用户鼠标悬停在信息点上时,通过射线投射实时检测鼠标位置对应的信息点,并显示相应的提示信息。

这种技术的优势在于能够在3D空间中实现精确的交互检测,无需复杂的碰撞检测算法,性能高效且实现简单。

项目中的具体实现细节

1. 射线投射基础设置

typescript
// 在 App.vue 中创建射线投射器和指针向量
let pointer = new THREE.Vector2(); // 存储归一化的鼠标坐标
let raycaster = new THREE.Raycaster(); // 射线投射器对象

2. 鼠标坐标归一化处理

typescript
// 将屏幕坐标转换为Three.js的标准化设备坐标
function normalizeMouseCoordinates(event: MouseEvent) {
  // X坐标:从 [0, window.innerWidth] 映射到 [-1, 1]
  pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
  
  // Y坐标:从 [0, window.innerHeight] 映射到 [1, -1]
  // 注意Y轴需要翻转,因为屏幕坐标Y轴向下,而Three.js坐标Y轴向上
  pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

3. 导航点击交互实现(RoomSprite.ts)

typescript
// 在 RoomSprite 类中实现点击检测
export class RoomSprite {
  sprite: THREE.Sprite;
  callbacks: any[]; // 存储点击回调函数

  constructor(
    text: string,
    position: THREE.Vector3,
    scene: THREE.Scene,
    camera: THREE.Camera
  ) {
    this.callbacks = [];
    
    // 创建导航精灵...
    
    // 监听全局点击事件
    window.addEventListener("click", (event) => {
      // 1. 归一化鼠标坐标
      pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
      pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
      
      // 2. 设置射线起点和方向
      raycaster.setFromCamera(pointer, camera);
      
      // 3. 检测射线与当前精灵的相交
      const intersects = raycaster.intersectObject(sprite);
      
      // 4. 如果有相交点,执行回调函数
      if (intersects.length > 0) {
        this.callbacks.forEach((callback) => callback());
      }
    });
  }

  // 添加点击回调函数
  onClick(callback: () => void) {
    this.callbacks.push(callback);
  }
}

4. 信息点悬停检测实现(App.vue)

typescript
// 存储所有信息点精灵的数组
const spriteList: THREE.Sprite[] = [];

// 信息点悬停显示函数
function tooltipShow(e: MouseEvent, spriteList: THREE.Sprite[]) {
  e.preventDefault();
  const pointer = new THREE.Vector2();
  const raycaster = new THREE.Raycaster();
  
  // 1. 归一化鼠标坐标
  pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
  pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
  
  // 2. 从相机位置发射射线
  raycaster.setFromCamera(pointer, camera);
  
  // 3. 检测射线与所有信息点的相交
  const intersects = raycaster.intersectObjects(spriteList);
  
  // 4. 处理相交结果
  if (intersects.length > 0) {
    // 检查是否为信息点类型
    if (intersects[0].object.userData.type === "information") {
      // 计算提示框在屏幕上的位置
      const element = e.target as HTMLElement;
      const elementWidth = element.clientWidth / 2;
      const elementHeight = element.clientHeight / 2;
      
      // 将3D世界坐标转换为屏幕坐标
      const worldVector = new THREE.Vector3(
        intersects[0].object.position.x,
        intersects[0].object.position.y,
        intersects[0].object.position.z
      );
      const position = worldVector.project(camera);
      
      // 计算提示框的屏幕位置
      const left = Math.round(
        (position.x + 1) * elementWidth - tooltipBox.value!.clientWidth / 2
      );
      const top = Math.round(
        -(position.y - 1) * elementHeight - tooltipBox.value!.clientHeight / 2
      );
      
      // 更新提示框位置和内容
      tooltipPosition.value = {
        left: `${left}px`,
        top: `${top}px`,
      };
      tooltipContent.value = intersects[0].object.userData;
    } else {
      // 如果不是信息点,隐藏提示框
      handleTooltipHide(e);
    }
  }
}

5. 信息点创建和注册

typescript
// 创建信息点并添加到检测列表
const infoSprite1 = new InfoSprite(
  "./images/dot.png",
  new THREE.Vector3(1.4, -0.2, -3),
  scene,
  {
    type: "information",
    name: "画",
    description: "这是一幅画",
  }
);

const infoSprite2 = new InfoSprite(
  "./images/dot.png",
  new THREE.Vector3(-2.4, 0.6, -3),
  scene,
  {
    type: "information",
    name: "木雕艺术品",
    description: "这是一件木雕艺术品",
  }
);

const infoSprite3 = new InfoSprite(
  "./images/dot.png",
  new THREE.Vector3(1.5, 0.4, 0.9),
  scene,
  {
    type: "information",
    name: "艺术画",
    description: "这是一幅艺术画",
  },
  0.1
);

// 将所有信息点添加到检测列表
spriteList.push(infoSprite1.sprite);
spriteList.push(infoSprite2.sprite);
spriteList.push(infoSprite3.sprite);

6. 事件监听器注册

typescript
// 注册鼠标移动事件监听器
renderer.domElement.addEventListener("mousemove", (e) => {
  tooltipShow(e, spriteList);
});

// 注册鼠标离开事件监听器
tooltipBox.value?.addEventListener("mouseleave", handleTooltipHide);

射线投射技术深度分析

1. 坐标系转换原理

typescript
// 屏幕坐标到标准化设备坐标的转换
/*
* 屏幕坐标系:
* - 原点在左上角
* - X轴向右为正,范围 [0, window.innerWidth]
* - Y轴向下为正,范围 [0, window.innerHeight]
*
* 标准化设备坐标系(NDC):
* - 原点在屏幕中心
* - X轴向右为正,范围 [-1, 1]
* - Y轴向上为正,范围 [-1, 1]
*/

// X坐标转换:[0, width] -> [-1, 1]
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;

// Y坐标转换:[0, height] -> [1, -1](注意翻转)
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;

2. 射线生成机制

typescript
// raycaster.setFromCamera() 的内部原理
/*
* 1. 根据相机类型(透视/正交)计算射线起点
* 2. 根据鼠标位置和相机参数计算射线方向
* 3. 对于透视相机:
*    - 起点:相机位置
*    - 方向:从相机位置指向屏幕上鼠标对应的3D点
*/
raycaster.setFromCamera(pointer, camera);

3. 相交检测算法

typescript
// intersectObjects() 的工作原理
/*
* 1. 遍历所有目标对象
* 2. 对每个对象执行射线-几何体相交测试
* 3. 计算相交点的距离
* 4. 按距离排序返回结果
* 
* 返回的 intersects 数组包含:
* - object: 相交的3D对象
* - distance: 相交点到射线起点的距离
* - point: 相交点的3D坐标
* - face: 相交的面(对于网格对象)
* - uv: 相交点的UV坐标
*/
const intersects = raycaster.intersectObjects(spriteList);

4. 3D到2D坐标投影

typescript
// 将3D世界坐标转换为屏幕坐标
const worldVector = new THREE.Vector3(
  intersects[0].object.position.x,
  intersects[0].object.position.y,
  intersects[0].object.position.z
);

// project() 方法的作用:
// 1. 应用相机的视图矩阵
// 2. 应用相机的投影矩阵
// 3. 执行透视除法
// 4. 返回标准化设备坐标 [-1, 1]
const position = worldVector.project(camera);

// 转换为屏幕像素坐标
const left = Math.round(
  (position.x + 1) * elementWidth - tooltipBox.value!.clientWidth / 2
);
const top = Math.round(
  -(position.y - 1) * elementHeight - tooltipBox.value!.clientHeight / 2
);

性能优化策略

1. 对象筛选优化

typescript
// 只对需要交互的对象进行射线检测
// 避免检测所有场景对象,提高性能
const intersects = raycaster.intersectObjects(spriteList); // 只检测精灵
// 而不是:raycaster.intersectObjects(scene.children, true); // 检测所有对象

2. 事件节流

typescript
// 在实际项目中可以添加节流,避免过于频繁的检测
let lastCheckTime = 0;
const CHECK_INTERVAL = 16; // 约60FPS

function throttledTooltipShow(e: MouseEvent, spriteList: THREE.Sprite[]) {
  const now = Date.now();
  if (now - lastCheckTime > CHECK_INTERVAL) {
    tooltipShow(e, spriteList);
    lastCheckTime = now;
  }
}

3. 距离优化

typescript
// 可以设置最大检测距离,避免检测过远的对象
raycaster.far = 100; // 只检测100单位内的对象

技术亮点和最佳实践

1. 类型安全的用户数据

typescript
// 在 InfoSprite 中使用 userData 存储类型信息
infoSprite.userData = {
  type: "information", // 用于区分对象类型
  name: "画",
  description: "这是一幅画",
};

// 在检测时进行类型判断
if (intersects[0].object.userData.type === "information") {
  // 处理信息点逻辑
}

2. 回调函数模式

typescript
// RoomSprite 使用回调函数模式,提高代码复用性
export class RoomSprite {
  callbacks: any[];
  
  onClick(callback: () => void) {
    this.callbacks.push(callback);
  }
}

// 使用时可以灵活添加不同的点击行为
balconySprite.onClick(() => {
  gsap.to(camera.position, { x: 0, y: 0, z: -10, duration: 1 });
});

3. 事件委托优化

typescript
// 使用全局事件监听器而不是为每个对象单独添加
// 这样可以减少事件监听器的数量,提高性能
window.addEventListener("click", handleGlobalClick);
renderer.domElement.addEventListener("mousemove", handleGlobalMouseMove);

应用场景扩展

1. 可能的扩展应用

  • 物体高亮:鼠标悬停时高亮显示可交互对象
  • 拖拽操作:实现3D对象的拖拽移动
  • 碰撞检测:检测移动对象与静态对象的碰撞
  • 选择框:实现框选多个3D对象
  • 测距工具:点击两点测量3D空间距离

2. 移动端适配

typescript
// 触摸事件的射线投射
function handleTouch(event: TouchEvent) {
  const touch = event.touches[0];
  pointer.x = (touch.clientX / window.innerWidth) * 2 - 1;
  pointer.y = -(touch.clientY / window.innerHeight) * 2 + 1;
  
  raycaster.setFromCamera(pointer, camera);
  // 执行相交检测...
}

技术总结

射线投射技术在我们的VR看房项目中发挥了关键作用:

  1. 精确交互:实现了像素级精确的3D空间交互检测
  2. 性能高效:相比复杂的碰撞检测算法,射线投射计算简单高效
  3. 易于实现:Three.js提供了完善的射线投射API,实现简单
  4. 扩展性强:可以轻松扩展到更多交互场景
  5. 用户体验:提供了直观自然的3D空间交互体验

这种技术的成功应用,使我们的VR看房应用具备了专业级的交互体验,是现代3D Web应用的核心技术之一。