首页 > 解决方案 > 使用 Javascript 进行命中检测

问题描述

我是一个初学者,几个月前开始写一些代码。

到目前为止,我已经使用 Javascript、HTML 和 CSS 构建了一个计算器。现在,我正在尝试使用 Javascript 和 HTML 制作平台游戏。

所以,我已经设置了播放器、障碍物、画布、框架和游戏结束功能。但我不知道命中检测是如何工作的。

所以,我试图这样做:

this.crashWith = function(otherobj) {

    //Declaring all the player and the obstacles position!
    
    //Player!
    var myLeft = this.x;
    var myRight = this.x + (this.width);
    var myTop = this.y;
    var myBottom = this.y + (this.height);

    //Obstacles!
    var otherLeft = otherobj.x;
    var otherRight = otherobj.x + (otherobj.width);
    var otherTop = otherobj.y;
    var otherBottom = otherobj.y + (otherobj.height);

    //Crash variables!
    var crash = true;

    if(
       //Checking the player location!
       (myBottom < otherTop) || 
       (myTop > otherBottom) || 
       (myRight < otherLeft) || (jump=true) ||
       (myLeft > otherRight) || (jump=true)
      )
     {
       /*
        If the player cordinates 
        is not touching the obstacles cordinate,
        crash is not happening/false.
       */

       crash = false;
     }

     if(
        (myTop == otherBottom) ||
        (myBottom == otherTop) || (jump=false)||
        (myLeft == otherRight) || (jump=false) ||
        (myRight == otherLeft) || (jump=false)
       )
     {
        crash = false;
     }

     return crash;
}

在我写第二个if语句之前,玩家在躲避障碍后总是在半空中冻结。我知道为什么会发生冻结,因为语句:

(myRight < otherLeft)

所以,为此我设置了跳转变量。

var jump;

if (myGameArea.keys && myGameArea.keys[32]) {myGamePiece.speedY = -2;} {jump=true} //jumping
if (myGameArea.keys && myGameArea.keys[83]) {myGamePiece.speedY = 1; }
//going down

//Left and right!
if (myGameArea.keys && myGameArea.keys[65]) {myGamePiece.speedX = -2; } // moving left
if (myGameArea.keys && myGameArea.keys[68]) {myGamePiece.speedX = 1; } //moving right

然后我写第二个 if 语句:

if(
    (myTop == otherBottom) ||
    (myBottom == otherTop) || (jump=false)||
    (myLeft == otherRight) || (jump=false) ||
    (myRight == otherLeft) || (jump=false)
  )
  {
    crash = false;
  }

在我写完第二个 if 语句后,不再冻结,但障碍就像幽灵一样。

完整代码:https ://codepen.io/ratpipe/pen/PoprLzV

标签: javascripthtmldebuggingcanvas

解决方案


jump不需要变量。您可以通过检查矩形之间是否没有间隙来检查矩形是否发生碰撞。在 Mozilla 的网络文档( 2D 碰撞检测)中找到了以下逻辑。

if(
  myLeft < otherRight &&
  myRight > otherLeft &&
  myTop < otherBottom &&
  myBottom > otherTop )
{
  crash = true;
}

您需要在游戏开始之前添加您的初始myObstaclemyObstaclesmyObstacles.push(myObstacle);以便您的游戏逻辑在此处检查:

for (i = 0; i < myObstacles.length; i += 1) {
  if (myGamePiece.crashWith(myObstacles[i])) {
    myGameArea.stop();
    return;
  }
}

推荐阅读