Konva haveIntersection js

问题描述

我是 konvas libray 的新手用户,我尝试制作了一个简单的游戏,我需要检测何时从形状中拖出框并显示警报“louser”,问题是形状不规则,因为检测事件的功能很好矩形形状,但不规则形状不尊重边框形式,我希望可以帮助我检测框何时拖出不规则形状并尊重边框,谢谢,代码如下

Konva Drag and Drop Multiple Shapes Demoview raw
<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/konva@7.2.2/konva.min.js"></script>
    <Meta charset="utf-8" />
    <title>Konva Drag and Drop Collision Detection Demo</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #f0f0f0;
      }
    </style>
  </head>

  <body>
    <div id="container"></div>
    <script>
      var width = window.innerWidth;
      var height = window.innerHeight;

      var stage = new Konva.Stage({
        container: 'container',width: width,height: height,});

      var layer = new Konva.Layer();
      stage.add(layer);

   
     
        var RectA = new Konva.Rect({
          x: 380,y:100,width: 30,height: 30,fill: 'grey',name: 'fillShape',draggable: true,stroke: 'red',hitstrokeWidth: 30,});
        
        
        
       
        
        var RectB = new Konva.Line({
          x: 350,y: 80,points:[0,50,100,100],closed: true,draggable: false,hitstrokeWidth: 10,tension: 1,});

        layer.add(RectB);
        layer.add(RectA);
        
      
      layer.draw();

      RectA.on('dragmove',function (e) {
        var target = e.target;
        
        var targetRect = e.target.getClientRect();
        layer.children.each(function (RectB) {
          // do not check intersection with itself
          if (RectB === target) {
            return;
          }
          if (haveIntersection(RectB.getClientRect(),targetRect)) {
           
          //  RectB.findOne('.fillShape').fill('red');
            
          } else {
          
           alert("louse");
           // RectB.findOne('.fillShape').fill('grey');
          }
          // do not need to call layer.draw() here
          // because it will be called by dragmove action
        });
      });

      function haveIntersection(r1,r2) {
      
      
      
        return !(
          r2.x > r1.x + r1.width ||
          r2.x + r2.width < r1.x ||
          r2.y > r1.y + r1.height ||
          r2.y + r2.height < r1.y
        );
      }
      
         layer.draw();
    </script>
  </body>
</html>

解决方法

我的建议是使用 Hitboxes

基本思想是用矩形标记您的复杂结构,然后查看每个矩形以查看是否存在连接。您可以使用下面的函数检查各个矩形。

Hitboxes 对于大多数结构来说并不完美,但如果您使用足够多,它的估计会非常准确。

此外,“专业”游戏也是如此。