📜  javascript 碰撞检测 - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:45.639000             🧑  作者: Mango

Javascript碰撞检测

碰撞检测在游戏和图形应用中很常见。Javascript可以实现多种类型的碰撞检测,比如:

  • 矩形碰撞检测
  • 圆形碰撞检测
  • 多边形碰撞检测
矩形碰撞检测

矩形碰撞检测是最简单和最基本的碰撞检测类型。下面是一个简单的矩形碰撞检测代码片段:

function rectCollision(rect1, rect2) {
  return rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x &&
         rect1.y < rect2.y + rect2.height && rect1.y + rect1.height > rect2.y;
}

其中,rect1rect2都是具有xywidthheight属性的对象。如果两个矩形重合,则返回true;否则返回false

圆形碰撞检测

圆形碰撞检测是另一种广泛使用的碰撞检测类型。下面是一个基本的圆形碰撞检测代码片段:

function circleCollision(circle1, circle2) {
  let dx = circle1.x - circle2.x;
  let dy = circle1.y - circle2.y;
  let distance = Math.sqrt(dx * dx + dy * dy);
  return distance < circle1.radius + circle2.radius;
}

其中,circle1circle2都是具有xyradius属性的对象。如果两个圆形重合,则返回true;否则返回false

多边形碰撞检测

多边形碰撞检测比较复杂,需要使用更多的数学公式。下面是一个基本的多边形碰撞检测代码片段:

function polygonCollision(poly1, poly2) {
  let overlap = Infinity;

  for (let i = 0; i < poly1.length; i++) {
    let axis = { x: poly1[i].y - poly1[(i + 1) % poly1.length].y,
                 y: poly1[(i + 1) % poly1.length].x - poly1[i].x };
    let min1 = Infinity;
    let max1 = -Infinity;
    for (let j = 0; j < poly1.length; j++) {
      let dot = poly1[j].x * axis.x + poly1[j].y * axis.y;
      if (dot < min1) min1 = dot;
      if (dot > max1) max1 = dot;
    }
    let min2 = Infinity;
    let max2 = -Infinity;
    for (let j = 0; j < poly2.length; j++) {
      let dot = poly2[j].x * axis.x + poly2[j].y * axis.y;
      if (dot < min2) min2 = dot;
      if (dot > max2) max2 = dot;
    }
    if (max1 < min2 || max2 < min1) {
      return false;
    } else {
      let o = Math.min(max1, max2) - Math.max(min1, min2);
      if (o < overlap) {
        overlap = o;
        smallestAxis = axis;
      }
    }
  }
  for (let i = 0; i < poly2.length; i++) {
    let axis = { x: poly2[i].y - poly2[(i + 1) % poly2.length].y,
                 y: poly2[(i + 1) % poly2.length].x - poly2[i].x };
    let min1 = Infinity;
    let max1 = -Infinity;
    for (let j = 0; j < poly1.length; j++) {
      let dot = poly1[j].x * axis.x + poly1[j].y * axis.y;
      if (dot < min1) min1 = dot;
      if (dot > max1) max1 = dot;
    }
    let min2 = Infinity;
    let max2 = -Infinity;
    for (let j = 0; j < poly2.length; j++) {
      let dot = poly2[j].x * axis.x + poly2[j].y * axis.y;
      if (dot < min2) min2 = dot;
      if (dot > max2) max2 = dot;
    }
    if (max1 < min2 || max2 < min1) {
      return false;
    } else {
      let o = Math.min(max1, max2) - Math.max(min1, min2);
      if (o < overlap) {
        overlap = o;
        smallestAxis = axis;
      }
    }
  }
  return { axis: smallestAxis, overlap: overlap };
}

其中,poly1poly2都是一个由{ x: number, y: number }对象组成的数组。如果多边形重合,则返回一个包含最小重叠量和最小重叠方向的对象;否则返回false

结论

以上是三种最常见的碰撞检测类型的代码片段。在实际应用中,碰撞检测往往需要结合具体情况进行调整和优化。