[英]how can i decrease delay in this.time.addEvent in phaser.js, based on score?
有人已经问过这个问题,但他们似乎没有得到正确的答案。
这是我的代码:
const eggGenLoop = this.time.addEvent({
delay: 1500 - (gameState.score * 100),
callback: eggGen,
callbackScope: this,
loop: true,
});
所以延迟不会改变,显然移相器只采用初始的gameState.score,即0。两个月前,我尝试使用纯JavaScript和setTimeout()/ setInterval()制作相同的游戏,但我偶然发现障碍,我希望使用 phaser.js 会更容易。
使用this.time.addEvent
和delay
将不起作用,因为TimerEvent
被创建一次。
我看到两个简单/快速的选择:
选项1)
您可以改为使用setTimeout
并递归调用它,并更新每次调用的delay
。
function setTimoutWithVariableDelta( score ){
setTimeout(
_ => {
// ... do some stuff
setTimoutWithVariableDelta( gameState.score );
},
1500 - (score * 100));
}
根据您的代码,此选项可能无法正常工作(顺便说一句: setTimeout
,当浏览器在后台时不会停止)。
选项 2)
或者您可以使用Scene
update
功能。
我将这种类型的动态延迟的逻辑放入函数callOnMuliplierInterval
中,它应该是直截了当的。 只需使用更新函数的time
参数来跟踪延迟。
(这里是文档的链接)
这是一个可能的例子:
(对不起,有点长,我走神了)
document.body.style = 'margin:0;'; var config = { type: Phaser.AUTO, width: 536, height: 203, scene: { create, update }, banner: false }; let interval = 2000; let lastRun = -1; let text1; let score = 1; let currentDelta = 1; let callsCount = 0; function create () { text1 = this.add.text(220, 30, `Score multiplier: ${score}`, { fontSize: '20px', fontStyle: 'bold', fontFamily:'Arial'}); let button1 = createButton(this, 40, 20, 0xff0000, '#ffffff', .5); let button2 = createButton(this, 40, 80, 0x0000ff, '#ffffff', .75); let button3 = createButton(this, 40, 140, 0x00ff00, '#ffffff', 1); } // demo helper function for creating buttons function createButton(scene, x, y, color, textColor, multiplier){ let button = scene.add.rectangle(x, y, 140, 40, color) .setOrigin(0); let buttonText = scene.add.text(10, 10, `Score ${multiplier}`, { fontSize: '20px', fontStyle: 'bold', fontFamily:'Arial', color: textColor}); Phaser.Display.Align.In.Center(buttonText, button); button.setInteractive().on('pointerdown', _ => { score = multiplier; text1.setText(`Score multiplier: ${score}`); }); return button; } // this function contains the important logic function callOnMuliplierInterval(time){ let newMessage = `Score multiplier: ${score}\n\n`; newMessage += `CurrentDelay: ${currentDelta}\nNextDelay: ${interval * score}\n`; newMessage += `Time: ${(time / 1000).toFixed(0)}s\n`; newMessage += `TimesCalled: ${callsCount}`; // Execute on: first Run or when the delay has passed if( lastRun == -1 || lastRun + currentDelta <= time ){ lastRun = time; currentDelta = interval * score; // HERE YOU WOULD DO THE ACTION callsCount++; } // Just update the message text1.setText(newMessage); } function update(time, delta){ callOnMuliplierInterval(time); } new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.