Javascript Canvas Side Detection

Hey, I'm trying to get the side that two objects in the canvas collide with. This is what I use to detect conflicts, but it only checks for collisions without a specific side.

Where o1 and o2 are objects that have properties:

x- position on the X axis
y- position on the Y axis
w- rectangle width
h- rectangle height

var collidesWith = function (o2) {
    var o1 = this;
    if ((o1.y + o1.h) < o2.y) {
        return 0;
    }
    if (o1.y > (o2.y + o2.h)) {
        return 0;
    }
    if ((o1.x + o1.w) < o2.x) {
        return 0;
    }
    if (o1.x > (o2.x + o2.w)) {
        return 0;
    }
    return 1;
};

EDIT : here is the code I appeared for collision detection at the top of the element:

if (
    (o1.y - o1.dy >= o2.y) &&
    (o1.y - o1.dy <= o2.y + o2.h) &&
    (o1.x + o1.w >= o2.x) &&
    (o1.x <= o2.x + o2.w)
) {
    // We have collision at the top end
}
+3
source share
1 answer

You need double conditions:

if ((o1.y > o2.y) && (o1.y < o2.y + o2.h)) {
  return 'top'; // o1 top border collided with o2 bottom border
}

Similarly for other parties.

+5
source

Source: https://habr.com/ru/post/1794270/


All Articles