gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:50:21 24 4
gpt4 key购买 nike

我正在尝试创建一个像 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
}

最佳答案

你在那里犯了几个错误:

  1. 当球上升时,你的碰撞检测器不工作(不需要检查 if (goingDown) ),因为碰撞可能发生在任何方向的球上。

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

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

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

enter image description here

当球到达矩形时,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;

}

关于javascript - 弹跳球在碰撞时错过了一些平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com