首页 > 解决方案 > AABB 分离轴定理,求重叠深度

问题描述

我想检测到 aabb 之间的冲突。我想要重叠量、穿透深度,以便我可以用这些信息将它们分开。

我试图理解下面的代码,在我的情况下它会产生错误的结果:例如:

对于 aabb [ x, y, width, height ], [0, 780, 60, 60] 和 [0, 606, 120, 240] 它会产生 xOverlap 60, yOverlap -23,而不是应该是 yOverlap 6。

/*
     * Collision Manifold
     * https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6\
    331#:~:text=Collision%20resolution%20is%20the%20act,allow%20them%20to%20remain%20intersecting.&text=The%20idea%20behind%20impulse%20res\
    olution,to%20separate%20objects%20found%20colliding.
     */
     function aabbvsaabb(a, b) {
    
      let normal,
          penetration;
    
      let n = [b.pos[0] - a.pos[0], b.pos[1] - a.pos[1]];
    
      let aExtent = a.width / 2,
          bExtent = b.width / 2;
    
       let xOverlap, yOverlap;
    
      xOverlap = aExtent + bExtent - Math.abs(n[0]);
    
      xOverlap = Math.min(xOverlap, Math.min(a.width, b.width));
    
      if (xOverlap > 0) {
    
        aExtent = a.height / 2,
        bExtent = b.height / 2;
    
    
        yOverlap = aExtent + bExtent - Math.abs(n[1]);
    
        yOverlap = Math.min(yOverlap, Math.min(a.height, b.height));
        if (yOverlap > 0) {
    
          if (xOverlap < yOverlap) {
            normal = n[0] < 0 ? [-1, 0]: [1, 0];
            penetration = xOverlap;
          } else {
            normal = n[1] < 0 ? [0, -1]:[0,1];
            penetration = yOverlap;
          }
    
        }
      }
    
   
          return {
            normal,
            xOverlap,
            yOverlap
          };
    };
    
 function rect(x, y, w, h) {
   return {
     x, y, width: w, height: h,
     pos: [x, y]
   };
 }
 
 let manifold = aabbvsaabb(rect(0, 780, 60, 60),
 rect(0, 606, 120, 240));
 
 console.log(manifold);

标签: javascriptcollision-detectiongame-physics

解决方案


推荐阅读