javascript - 使用 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 语句后,不再冻结,但障碍就像幽灵一样。
解决方案
jump
不需要变量。您可以通过检查矩形之间是否没有间隙来检查矩形是否发生碰撞。在 Mozilla 的网络文档( 2D 碰撞检测)中找到了以下逻辑。
if(
myLeft < otherRight &&
myRight > otherLeft &&
myTop < otherBottom &&
myBottom > otherTop )
{
crash = true;
}
您需要在游戏开始之前添加您的初始myObstacle
值myObstacles
,myObstacles.push(myObstacle);
以便您的游戏逻辑在此处检查:
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
myGameArea.stop();
return;
}
}
推荐阅读
- java - 无法使用 FEST/swing 在辅助窗口上执行操作
- r - object_usage_linter 标记错误的行,没有可见的绑定消息
- python - 将 API 响应附加到单个 JSON 文件
- logging - 登录 Netlogo 网站
- python - 仅当存在一个具有空值的后续行时,才在数据框中前向填充一列
- c# - 当某些 LogicalThreadContext.Property 在 log4net 中具有特定值时如何忽略日志
- c# - asp.net core 2.2 razor 页面登录不持久。很快用户必须重新登录
- android - 任务 ':expo-constants:compileDebugJavaWithJavac' 执行失败。(反应原生)
- angular - 更改 Angular 7 中的 webpack 配置并更改 CKEditor 5 的 SVG 设置以加载自定义插件
- c++ - 是否可以仅通过在 C++ 中存储分配的指针地址来分析内存?