JavaScript 游戏碰撞

JavaScript game Collision

在线性格斗游戏中,我使用下面的公式来获得 X 碰撞和 Y 碰撞(当角色跳到另一个战士的顶部时)。 我真的不知道这个公式有什么问题,因为我在游戏中遇到了一些无意义的逻辑错误。(当碰撞发生时,我向前和向后移动角色,所以有时我会得到无意义的位置。 除了我的公式,如果您还有其他公式,请分享。谢谢

    if (this.x < secondPlayer.x + secondPlayer.width + this.border &&
        this.x + this.width + this.border > secondPlayer.x && this.y < secondPlayer.y + secondPlayer.height + this.border &&
        this.height + this.y + this.border > secondPlayer.y && this.x != secondPlayer.x){
            return 'x';
        }
        else if (this.x == secondPlayer.x && this.y < secondPlayer.y + secondPlayer.height + this.border &&
            this.height + this.y + this.border > secondPlayer.y) {
                return 'y';
     }else{
         return 'n';
     }

我没有时间给你一个准确的答案,只是把你重定向到bounding boxes。定义一个像矩形的结构并检查边框,如 link:

myBox.x = this.x 
myBox.y = this.y
myBox.width = this.width + this.border
myBox.height = this.height + this.border

你也可以有不同的方法:

myBox.left = this.x 
myBox.top = this.y
myBox.right = this.x + this.width + this.border
myBox.bottom = this.y + this.height + this.border

并检查: 左对右,上对下,反

编辑: 使用您的代码,您不能同时检查两个碰撞:您的代码说:

if (x collides) return 'x' else if (y collides) return 'y'

因此,如果您有 'x' 碰撞,函数 returns 不会检查 'y'。 此外,在第二个测试中,我认为 this.x == secondPlayer.x 是错误的:'y' 仅当两个玩家的位置相同时才检查碰撞。但是它们可以重叠而不是在同一个 'x' (例如,我跳起来并落在对手的精灵中间)!