首页 > 解决方案 > 条件为假时如何暂停

问题描述

我正在制作一个游戏,我想在一个条件为真和一个表达式正在运行之间暂停一下。下面的注释行显示了我想要暂停的位置,我想要的暂停类型是这样的(不起作用):

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;


        }

    }

},

标签: javascript

解决方案


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,因此您需要调整使用它的其他代码位,因此您正在等待(并在必要时等待这些函数)。


推荐阅读