为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_花开花谢_0 2021-09-17 16:25:48
我正在尝试创建一个像 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  }
查看完整描述

2 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

你在那里犯了几个缺陷:

  1. 当球上升时,您的碰撞检测器不起作用(无需检查if (goingDown)),因为球在任何方向行进都可能发生碰撞。

  2. 第二个缺陷是您正在测量从球中心到矩形中心的距离。当球与矩形的远端碰撞时,您将不会检测到碰撞。像这样:

//img1.sycdn.imooc.com//6144512a0001294f05000193.jpg

dist <= r 为 FALSE,因此未检测到碰撞

您需要的是计算到矩形上最近点的圆心距离,如下所示:

//img1.sycdn.imooc.com//6144513600011dde05000226.jpg

当球到达矩形时, dist <= r 将为 TRUE。


在修复这些缺陷的同时,我们得到了这样的碰撞检测功能:


checkPlatformCollision(platforms) {


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

      let NearestX = Math.max(platforms[j].x, Math.min(this.x, platforms[j].x + platformWidth));

      let NearestY = Math.max(platforms[j].y, Math.min(this.y, platforms[j].y + platformHeight));


        let dx = Math.abs(this.x - NearestX);

        let dy = Math.abs(this.y - NearestY);


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

          return true;

        }


       }


      return false;


  }


查看完整回答
反对 回复 2021-09-17
?
米脂

TA贡献1836条经验 获得超3个赞

似乎进行以下更改解决了问题。现在碰撞检测工作得很好。


checkPlatformCollision(platforms) {

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

      if (

        (goingDown) &&

        (this.x < platforms[j].x + platformWidth) &&

        (this.x + this.r > platforms[j].x) &&

        (this.y + this.r > platforms[j].y) &&

        (this.y + this.r < platforms[j].y + platformHeight)

        ) {

          return true

      }

    }

    return false

  }



查看完整回答
反对 回复 2021-09-17
  • 2 回答
  • 0 关注
  • 186 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号