javascript - 条件为假时如何暂停
问题描述
我正在制作一个游戏,我想在一个条件为真和一个表达式正在运行之间暂停一下。下面的注释行显示了我想要暂停的位置,我想要的暂停类型是这样的(不起作用):
while (bullet.yPos >= 0) {}; //Tried, failed
所以我希望我的代码在 bullet.yPos
大于或等于 0 时停止,然后在bullet.yPos
小于 0 时继续。
bullet.hidden = true;
//I want the pause here, and the line below to be executed when bullet.yPos is less than 0
bullet.hidden = false;
我该怎么做?
编辑:这是相关的方法:
check: function() {
for (var i = 0; i < this.aliens.length; i++) {
var item = this.aliens[i];
if ((bullet.lockedXPos >= item.xPos) && (bullet.lockedXPos <= item.xPos + this.size) && (bullet.yPos >= item.yPos) && (bullet.yPos <= item.yPos + this.size)) {
item.hit = true;
bullet.hidden = true;
while (bullet.yPos >= 0) {};
bullet.hidden = false;
}
}
},
解决方案
Promise
您可以与实例一起创建一个。我在这里进行了简化,但总体思路就在那里。
const yGreaterThanZero, { resolve } = new Promise();
现在,在您提供的方法中,您可以使用await yGreaterThanZero
,这正是您所期望的
check: async function() {
for (var i = 0; i < this.aliens.length; i++) {
var item = this.aliens[i];
if ((bullet.lockedXPos >= item.xPos) && (bullet.lockedXPos <= item.xPos + this.size) && (bullet.yPos >= item.yPos) && (bullet.yPos <= item.yPos + this.size)) {
item.hit = true;
bullet.hidden = true;
// while (bullet.yPos >= 0) {};
await yGreaterThanZero; // this bit here is key
bullet.hidden = false;
}
}
},
此外,在您更新的地方bullet.yPos
,您需要添加以下内容:
if (bullet.yPos >= 0) resolve();
当然,变量名应该是语义的,所以你不应该只调用它resolve
。但是,这应该足以等待某个条件,前提是您还告诉 JS何时该条件发生。
重要说明:该函数是 made async
,因此您需要调整使用它的其他代码位,因此您正在等待(并在必要时等待这些函数)。
推荐阅读
- python - 如何 brew 安装 matplotlib 和 pandas?(自制安装)
- regression - 为什么使用综合得分时路径分析会失败?
- php - 在 s3 上上传文件:无法打开流:没有这样的文件或目录
- angular - 角度 Slickgrid 中的可编辑和不可编辑单元格
- java - How to check whether all elements of a JSON array start with a specific string?
- c# - 由于绑定错误,Azure Webjob 无法启动
- azure - 在生产环境中运行 Azure API 管理开发人员层
- javascript - 使用包含索引的字符串设置对象的嵌套值
- javascript - 文档上的 mouseenter 和 mouseleave 事件侦听器在 Firefox 中不起作用
- python - BeautifulSoup find_all(text=True) 没有打印任何东西?