This is my first time posting a question in Stack Overflow, so feel free to comment on how I can improve my question as well.
I am trying to make two SVG rectangle draggables which cannot overlap. To do this, I have used Snap.svg to make the elements drag, and have taken their bounding boxes with every call of the move function to see if they collide, using the .isBBoxIntersect utility method in the Snap API. If they do collide, I want to make sure they will not overlap, and thus make each object unpassable to the other. The object currently being dragged will then move on a certain axis, until the collision returns false once more. I have some basic code of what I want here:
<html>
<head>
<title>
</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.4.1/snap.svg-min.js"></script>
</head>
<body>
<script>
var s = Snap(600,500);
var rect = s.rect(0,0,40,40);
var rectr = s.rect(400,90,50,50);
var b=0;
var c=0;
var isInter;
var move = function(dx,dy, x, y, event) {
var b1 = rect.getBBox();
var b2 = rectr.getBBox();
isInter = Snap.path.isBBoxIntersect(b1, b2);
if (isInter==false) {
b=dx;
c=dy;
}
if (isInter==true) {
if (b1.y2==b2.y&&b1.x2==b2.x||b1.x==b2.x2&&b1.y2==b2.y){c=b2.y-b1.h, b=dx
}
else if (b1.x==b2.x2&&b1.y==b2.y2||b1.x2==b2.x&&b1.y==b2.y2){c=b2.y2; b=dx;}
else if (b1.y2==b2.y){(dy>=b2.y-b1.h) ? (c=b2.y-b1.h, b=dx): (b=dx, c=dy);}
else if (b1.y==b2.y2){(dy<=b1.y) ? (c=b2.y2, b=dx):(b=dx,c=dy);}
else if (b1.x2==b2.x){(dx>=b1.x) ? (b=b2.x-b1.width, c=dy):(b=dx, c=dy);}
else if (b1.x==b2.x2){(dx<=b1.x2) ? (b=b2.x2, c=dy):(b=dx, c=dy);}
else {b=dx; c=dy;}
}
this.attr({
transform: this.data('origTransform') + ((this.data('origTransform')) ? "t": "T") + [b,c]
});
}
var start = function() {
this.data('origTransform', this.transform().local );
b=0;
c=0;
}
rect.drag(move, start);
circle.drag(move, start);
</script>
</body>
</html>
These are the three main issues that came up:
If you drag too fast, the engine can't keep up, and the draggables will overlap. I'm hoping for a method to prevent overlap no matter how fast it is dragged.
The collision only works for rect when it is dragged on rectr. I could easily add another block of collision detection for rectr on rect, but I think that would slow the engine WAY too much. My collision detection seems overly complex. Thus, I'm hoping for a more efficient way to test the collision.
If rectr is dragged first, then rect is dragged on rectr, the collision detection completely fails. It might be an issue of .getBBox(), but I can't say for certain.
Any help on these three issues would be extremely appreciated.
Thank You!