【问题标题】:Collision detection of each side not working每一侧的碰撞检测不起作用
【发布时间】:2018-07-23 19:28:35
【问题描述】:

我最近一直在开发一个 2D 平台游戏,它有多个角色可以在它们之间切换。我想实现碰撞检测,循环遍历每个角色,并根据他们触摸的哪一侧阻止它移动。基本上这样角色就可以相互跳跃而不能相互穿过。我使用了 AABB Intersect 碰撞检测系统,然后确定我击中了角色的哪一侧,我使用了以下代码:

for (var a = 0; a < this.characters.length; a++) {
  for (var b = 0; b < this.characters.length; b++) {
    if (a !== b) {
      if (this.characters[a].collision(this.characters[b])) {
        var ab = this.characters[a].y + this.characters[a].height,
          ar = this.characters[a].x + this.characters[a].width,
          bb = this.characters[b].y + this.characters[b].height,
          br = this.characters[b].x + this.characters[b].width;

        var tc = ab - this.characters[b].y,

          bc = bb - this.characters[a].y,

          lc = ar - this.characters[b].x,

          rc = br - this.characters[a].x;

        // Bottom is touching something
        if (tc < bc && tc < lc && tc < rc) {
          this.characters[a].isJumping = false;
          this.characters[a].vel.y = 0;
          this.characters[a].y = this.characters[b].y - this.characters[a].height;
        }

        // Top is touching something
        if (bc < tc && bc < lc && bc < rc) {
          this.characters[a].isJumping = false;
          this.characters[a].y = this.characters[b].y + this.characters[b].height;
        }

        // Right side is touching something
        if (lc < rc && lc < tc && lc < bc) {
          this.characters[a].x = this.characters[b].x - this.characters[a].width;
        }

        // Left side is touching something
        if (rc < lc && rc < tc && rc < bc) {
          this.characters[a].x = this.characters[b].x + this.characters[b].width;
        }
      }
    }
  }
}

对于第一个字符(块;我没有提到这一点,但是,所有字符都是正方形)似乎工作正常,但是如果我尝试使用第二个字符(字符在数组)并测试第一个字符的碰撞。诸如在不工作的顶部跳跃和向左走进角色导致第一个角色向左移动(我知道为什么会发生这种情况,但是,我不知道如何解决它)之类的事情。第三个角色对前两个角色不起作用,然后到第四个角色完全混乱。有人有什么建议吗?

【问题讨论】:

  • 我认为您可以检查角色是否与某物发生碰撞,以及是否是角色或块执行该代码。

标签: javascript collision-detection game-physics


【解决方案1】:

一次碰撞会在你的循环中造成两次碰撞,首先是a = 0 和碰撞对象b = 1(例如),然后是a = 1b = 0 时,将再次检测到相同的碰撞。

我认为最好使用一组非活动字符来检查一个活动字符。

您可以在玩家切换角色时创建这些变量。这样你只需要一个循环,你不需要if a != b检查

这段代码说明了这个想法:

function characterChange(){
   activeCharacter = objA;
   inActiveCharacters = [objB, objC, objD];
}

function checkCollisions(){
   for(let i = 0; i<inActiveCharacters.length; i++){
      checkHit(activeCharacter, inActiveCharacters[i]);
   }
}

function checkHit(a,b) {
    // your a b check here
}

【讨论】:

  • 我以前做过。但是,如果我需要在非活动角色之间进行碰撞检测怎么办?有没有办法做到这一点?
猜你喜欢
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多