弹跳球碰撞时错过了一些平台

我正在尝试创建一个像 Doodle Jump 一样的演示游戏,但我陷入了最愚蠢的情况。在检查碰撞时,我的弹跳球只是错过了一些平台(落下)。


对此有何想法?Codepen 跟随寻求帮助。


我试过对数组中的平台进行排序(认为这是错误),当然无济于事。


这是我用于展示案例的 codepen 示例。 https://codepen.io/v4vaios/pen/ZEzpozg


    checkPlatformCollision(platforms) {

    if (goingDown) {


      for(let j=0; j<platforms.length; j++) {

        let distX = Math.abs(this.x - platforms[j].x-platformWidth/2);

        let distY = Math.abs(this.y - platforms[j].y-platformHeight/2);

        let dx=distX-platformWidth/2;

        let dy=distY-platformHeight;


        if (dx*dx + dy*dy <= (this.r*this.r)) {

          return true

        }



      }

    }


    return false

  }


qq_花开花谢_0
浏览 187回答 2
2回答

HUX布斯

你在那里犯了几个缺陷:当球上升时,您的碰撞检测器不起作用(无需检查if (goingDown)),因为球在任何方向行进都可能发生碰撞。第二个缺陷是您正在测量从球中心到矩形中心的距离。当球与矩形的远端碰撞时,您将不会检测到碰撞。像这样:dist <= r&nbsp;为 FALSE,因此未检测到碰撞您需要的是计算到矩形上最近点的圆心距离,如下所示:当球到达矩形时, dist <= r 将为 TRUE。在修复这些缺陷的同时,我们得到了这样的碰撞检测功能:checkPlatformCollision(platforms) {&nbsp; &nbsp; &nbsp; for(let j=0; j<platforms.length; j++) {&nbsp; &nbsp; &nbsp; let NearestX = Math.max(platforms[j].x, Math.min(this.x, platforms[j].x + platformWidth));&nbsp; &nbsp; &nbsp; let NearestY = Math.max(platforms[j].y, Math.min(this.y, platforms[j].y + platformHeight));&nbsp; &nbsp; &nbsp; &nbsp; let dx = Math.abs(this.x - NearestX);&nbsp; &nbsp; &nbsp; &nbsp; let dy = Math.abs(this.y - NearestY);&nbsp; &nbsp; &nbsp; &nbsp; if (dx*dx + dy*dy <= (this.r*this.r)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; return false;&nbsp; }

米脂

似乎进行以下更改解决了问题。现在碰撞检测工作得很好。checkPlatformCollision(platforms) {&nbsp; &nbsp; for(let j=0; j<platforms.length; j++) {&nbsp; &nbsp; &nbsp; if (&nbsp; &nbsp; &nbsp; &nbsp; (goingDown) &&&nbsp; &nbsp; &nbsp; &nbsp; (this.x < platforms[j].x + platformWidth) &&&nbsp; &nbsp; &nbsp; &nbsp; (this.x + this.r > platforms[j].x) &&&nbsp; &nbsp; &nbsp; &nbsp; (this.y + this.r > platforms[j].y) &&&nbsp; &nbsp; &nbsp; &nbsp; (this.y + this.r < platforms[j].y + platformHeight)&nbsp; &nbsp; &nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript