如何实现碰撞检测?

解读

碰撞检测是游戏开发、图形交互等场景中的核心功能,需判断两个对象是否发生重叠。在TypeScript面试中,该问题考察候选人对类型系统、接口设计、泛型应用及实际开发场景的综合理解。需结合TypeScript特性(如类型注解、类型推断)实现健壮且可维护的检测逻辑,同时体现对主流框架(如React、Vue)集成能力的掌握。

知识点

  1. 类型系统与类型安全:通过类型注解确保坐标、尺寸等参数类型正确,避免运行时错误。
  2. 接口与多态:定义统一的形状接口(如Shape),支持不同子类(如Circle、Rectangle)的碰撞检测方法。
  3. 泛型编程:使用泛型实现通用的碰撞检测函数,适应不同形状类型。
  4. 模块化设计:将碰撞检测逻辑封装为独立模块,便于复用与维护。
  5. 性能优化:结合TypeScript的类型信息进行编译时优化,提升检测效率。

答案

在TypeScript中实现碰撞检测,需结合类型系统与几何算法。以下是分层实现方案:

1. 定义形状接口

interface Shape {
  x: number;
  y: number;
  width?: number;
  height?: number;
  radius?: number;
}

通过可选属性(?)区分不同形状类型,如Rectangle需width和height,而Circle需radius。

2. 实现具体形状类

class Rectangle implements Shape {
  x: number;
  y: number;
  width: number;
  height: number;
  constructor(x: number, y: number, width: number, height: number) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }
}

class Circle implements Shape {
  x: number;
  y: number;
  radius: number;
  constructor(x: number, y: number, radius: number) {
    this.x = x;
    this.y = y;
    this.radius = radius;
  }
}

利用类实现接口,确保形状对象具备统一的属性结构。

3. 编写通用碰撞检测函数

function detectCollision(shape1: Shape, shape2: Shape): boolean {
  // 类型守卫区分形状类型
  if (shape1.radius !== undefined && shape2.radius !== undefined) {
    // 圆形与圆形碰撞:使用距离公式
    const dx = shape1.x - shape2.x;
    const dy = shape1.y - shape2.y;
    return Math.sqrt(dx * dx + dy * dy) <= shape1.radius + shape2.radius;
  } else if (shape1.width !== undefined && shape1.height !== undefined && shape2.width !== undefined && shape2.height !== undefined) {
    // 矩形与矩形碰撞:使用轴对齐包围盒(AABB)检测
    return (
      shape1.x < shape2.x + shape2.width &&
      shape1.x + shape1.width > shape2.x &&
      shape1.y < shape2.y + shape2.height &&
      shape1.y + shape1.height > shape2.y
    );
  } else {
    // 混合形状(如矩形与圆形)需额外处理
    throw new Error("Unsupported shape combination");
  }
}

通过类型守卫(if判断)实现多态,确保函数能处理不同形状组合,同时利用类型系统避免非法参数传递。

4. 模块化封装

将检测逻辑封装为独立模块,支持扩展性:

// collision.module.ts
export interface Shape { ... }
export class Rectangle { ... }
export class Circle { ... }
export function detectCollision(shape1: Shape, shape2: Shape): boolean { ... }

模块化设计便于在大型项目中复用,并通过TypeScript的模块系统确保类型定义的准确性。

拓展思考

  1. 复杂形状处理:如何通过泛型支持多边形碰撞检测?可定义Polygon接口并使用类型参数动态处理顶点数组。
  2. 性能优化:在WebGL中,如何结合TypeScript的类型信息进行空间分区(如网格划分)以降低检测复杂度?
  3. 框架集成:在React中,如何通过TypeScript的组件类型定义(如props接口)实现碰撞检测状态管理?
  4. 类型推断应用:是否可通过函数重载或联合类型(|)简化碰撞检测函数的调用?例如:
function detectCollision(a: Rectangle, b: Rectangle): boolean;
function detectCollision(a: Circle, b: Circle): boolean;
function detectCollision(a: Shape, b: Shape): boolean { ... }

此方案利用类型推断提升代码可读性,但需注意类型兼容性问题。