Javascript collision detection system don't ignore blocked collisions

回眸只為那壹抹淺笑 提交于 2019-12-01 19:59:37

You have to treat horizontal and vertical collisions independently.

I've made some minor changes to your JS-fiddle: http://jsfiddle.net/Kf6cv/1/ it should work now, what I did is I split up your one check into two:

if (nextposy + height(circle) > rect.y &&
    circle.x + width(circle) > rect.x &&
    circle.x < rect.x + rect.width &&
    nextposy < rect.y + rect.height) {
    if (circle.y + height(circle) < rect.y) {
       cls("top");
    }
    if (circle.y > rect.y + rect.height) {
        cls("bottom");
    }
}

if (nextposx + width(circle) > rect.x &&
    nextposx < rect.x + rect.width &&
    circle.y + height(circle) > rect.y &&
    circle.y < rect.y + rect.height) {
    if (circle.x + width(circle) < rect.x) {
        cls("left");
    }
    if (circle.x > rect.x + rect.width) {
        cls("right");
    }
}

The reason for this is that if check both directions at once, it will prevent the movement(or make it bounce) for both directions(like the red figure in your picture) - even if it COULD move into one direction. The order of checking horizontal/vertical usually doesn't matter, it usually only matters if your "hero" approaches the other object 100% edge-to-edge. But what you could to is to first check the direction with the higher velocity, so if |velX| > |velY| then you first check for a horizontal collision.

Also I'd say it is safer to apply the new position directly after checking, right now it does two independend checks and then applies the movement of both directions - I'm not to sure about it but I could imagine that this might lead to some issues later.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!