处于非活动状态 5 秒后结束游戏

End the game after 5 seconds of inactivity

本文关键字:结束 游戏 于非 活动状态      更新时间:2023-09-26

我是 Phaser.io 新手,所以如果这篇文章不好,我深表歉意。

5

秒不活动后如何结束游戏?我做了一些东西,但我认为这对性能真的很糟糕。每次调用更新函数时,我都会检查用户是否没有按"向上、向左、向右、向下",并在我检查我们是否超过了时间之后(当前时间 - 开始时间> 5000)。这段代码有 2 个我试图触发的问题:- 性能真的很差,因为每次调用更新函数时都不需要检查- 在我的条件下,我想检查"没有按键被按下",现在我只是检查用户是否没有按"向上"、"向左"、"向右"或"向下"

怎么办呢?对不起我的英语

var timeBeginning = new Date().getTime();
function update() {
    // input to move the ship
    if (cursors.up.isDown) {
        game.physics.arcade.accelerationFromRotation(ship.rotation, 200, ship.body.acceleration);
    } else {
        // stopper the acceleration 
        ship.body.acceleration.set(0);
    }
    if (cursors.left.isDown) {
        ship.body.angularVelocity = -300;
    } else if (cursors.right.isDown) {
        ship.body.angularVelocity = 300;
    } else {
        // stop the rotation
        ship.body.angularVelocity = 0;
    }
    if (!cursors.up.isDown && !cursors.left.isDown && !cursors.right.isDown && !cursors.down.isDown) {
        if (new Date().getTime() - timeBeginning > 5000) {
            end();
        }
    } else {
        timeBeginning = new Date().getTime();
    }
}

您可以通过 game.input.keyboard.addCallbacks 添加全局键盘事件侦听器

var timeBeginning = Date.now();
function create(){
    function updateTime(){
        timeBeginning = Date.now();
    }
    game.input.keyboard.addCallbacks(game, updateTime, updateTime);
}
function update() {
    //your code
    if (Date.now() - timeBeginning > 5000) {
        end();
    }
}