5

嘿,我正在尝试获取画布中两个对象碰撞的一侧。这是我用于碰撞检测的内容,但它只检查碰撞,没有特定的一面。

其中 o1 和 o2 是具有属性的对象:

x- X 轴上的
y位置 - Y 轴上的位置
w- 矩形的宽度 - 矩形
h的高度

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;
};

编辑:这是我为元素顶部的碰撞检测提出的代码:

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
}
4

1 回答 1

8

你需要这样的双重条件:

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

其他方面也是如此。

于 2011-02-23T22:44:24.127 回答