如何在 Phaser 框架中显示当前时间?

How to show the current time in Phaser framework?

我似乎找不到有关如何在 Phaser 框架中显示当前时间的示例。我已经经历了 examples on the official site, and all I could come up are the example where the timer is counting down, or up toward something (like this example,例如,双关语 :)).

因为实在找不到官方的例子,所以放在这里,仅供参考,希望对和我搜索相同查询词的人有所帮助.

似乎比我想象的要容易。简单地说,使用 JavaScript 函数更新 update 方法中的文本,returns 需要使用 Date 对象的时间信息:

var timeText = game.add.text(10, 10, "00:00:00");
function update(){
    timeText.setText(getCurrentTime());
}

function getCurrentTime(){
    var currentdate = new Date(); 
    var time = currentdate.getHours() + ":"  + currentdate.getMinutes() + ":" + currentdate.getSeconds();
    return time;
}

您的示例将起作用。但是,它会在每次更新时检查时间(运行 每帧一次),这在计算上更加昂贵并且可能会减慢您的游戏速度。这是一个带有每秒更新时间的计时器的解决方案:

var timeString;
var timeText;

function create() {
    var style = { fill : "#FFFFFF" };
    timeText = game.add.text(200, 200, timeString, style);

    var timer = game.time.create();
    timer.repeat(1 * Phaser.Timer.SECOND, 7200, updateTime, this);
    timer.start();
}

function updateTime() {
    var time = new Date();

    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();

    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }

    timeString = hours + ":" + minutes + ":" + seconds;
    timeText.text = timeString;
}

Link to Phaser Sandbox with this example