Javascript 矩形碰撞

Javascript rectangle collision

我正在处理 2D 非旋转矩形碰撞。我可以检测到它,并得到交集 width/height/position,但我无法 "cancel" 它。这是我试过的 "cancelling" 代码:

if (this.bounds.intersects(player.bounds)) {
    var intersection = this.bounds.intersection(player.bounds);
    if (player.bounds.bottomRight().x > this.position().x)
        player.position().subtract(intersection.width, 0);
    else if (player.position().x > this.position().x)
        player.position().add(intersection.width, 0);
    else if (player.bounds.bottomRight().y > this.position().y)
        player.position().subtract(0, intersection.height);
    else if (player.position().y > this.position().y)
        player.position().add(0, intersection.height);
}

(相交和相交方法有效)

"this" 是一堵玩家应该无法穿过的墙。 这是目前的效果:

玩家是红色方块,墙是黑色方块。 我该如何解决这个问题?

我不确定你的函数是如何相交和交叉工作的,但我建议你根据 intersection.width < intersection.height 或不根据

来单独更新播放器,比如

if (this.bounds.intersects(player.bounds)) {
    var intersection = this.bounds.intersection(player.bounds);
    if(intersection.width < intersection.height){
        if (player.bounds.bottomRight().x > this.position().x)
            player.position().subtract(intersection.width, 0);
        else if (player.position().x > this.position().x)
            player.position().add(intersection.width, 0);
    }else{
        if (player.bounds.bottomRight().y > this.position().y)
            player.position().subtract(0, intersection.height);
        else if (player.position().y > this.position().y)
            player.position().add(0, intersection.height);
    }
}

根据您检测到碰撞的程度,这可能或多或少会起作用。