Search code examples
html5-canvaskineticjs

How to determine a shape touches another shape or not using kineticjs?


I have a number of shapes in my kinetc layer. If I drag and drop a shape somewhere else in the layer, how to determine the dropped shape touches another shape or not?


Solution

  • The thing you need to do is create a mathematical representation of the shapes you have. For most simple collision detection, you can use bounding-boxes.

    Basically, if you have a circle, you can create a representation of it as being bounded in a box.
    Then if you have a square, you can check if the bounding box of the square (which is the square itself) is intersecting with the bounding box of the circle.

    I wrote an answer to this a while ago: HTML5 / kineticJS getIntersection function implementation

     function checkCollide(pointX, pointY, objectx, objecty, objectw, objecth) { // pointX, pointY belong to one rectangle, while the object variables belong to another rectangle
          var oTop = objecty;
          var oLeft = objectx; 
          var oRight = objectx+objectw;
          var oBottom = objecty+objecth; 
    
          if(pointX > oLeft && pointX < oRight){
               if(pointY > oTop && pointY < oBottom ){
                    return 1;
               }
          }
          else
               return 0;
     };
    

    used like this:

     var children = layer.getChildren();
     for( var i=0; i<children.length; i++){  // for each single shape
         for( var j=0; j<children.length; j++){ //check each other shape
             if(i != j){ //skip if shape is the same
                if(checkCollide(children[i].getX(), children[i].getY(), children[j].getX(), children[j].getY(), children[j].getWidth(), children[j].getHeight()))
                    alert('top left corner collided');
             }
         }
     }
    

    This works great if the shape you have is a rectangle of some sort, but not that great if you have two circles, as they have a radius. So this suffices for a quick check of collision, next you need another function which will check collisions more precisely.

    You can also try using kineticjs with box2d, there are a bunch of tutorials out there on the topic.