html - Javascript canvas collision side detection - Stack Overflow

Hey i'm trying to get the side with which the two objects in the canvas collide. Here's what

Hey i'm trying to get the side with which the two objects in the canvas collide. Here's what i'm using for collision detection, but it only checks for a collision, without a specific side.

Where o1 and o2 are objects taht have properties:

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

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's the code i came up for the collision detection on 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
}

Hey i'm trying to get the side with which the two objects in the canvas collide. Here's what i'm using for collision detection, but it only checks for a collision, without a specific side.

Where o1 and o2 are objects taht have properties:

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

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's the code i came up for the collision detection on 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
}
Share Improve this question edited Feb 27, 2011 at 11:49 Pockata asked Feb 23, 2011 at 22:26 PockataPockata 1,5783 gold badges13 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You need double-conditions like this:

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

Similarily for other sides.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742392584a4435306.html

相关推荐

  • html - Javascript canvas collision side detection - Stack Overflow

    Hey i'm trying to get the side with which the two objects in the canvas collide. Here's what

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信