因此,当玩家按下x时,我的 Angular 色div会更改其背景图像,如果 Angular 色触摸敌人,它就会杀死敌人。此图像开关用于做挥舞剑的模拟动画。
我使用set timeout来延迟将背景图像切换回其原始状态。这行得通。
但是是一个错误,即如果我发送x垃圾邮件,图像切换之间将不再存在延迟,并且我推测这与堆叠setTimeout函数中的异步回调有关,该原因是在播放器向x垃圾邮件发送时被调用的。
**此功能中设置了超时**
function pressOn(e) {
e.preventDefault();
let tempKey = (e.key == " ") ? "space" : e.key;
keys[tempKey] = true;
if (keys['x'] && player.swing == false){
player.plane.style.backgroundImage ='url(guts2.png)';
setTimeout(function () {
player.swing = true;
}, 300);
}
}
**原始背景图像**
function playGame() {
if (player.inplay) {
if (player.swing && !keys['x']){
player.plane.style.backgroundImage ='url(guts1.png)';
player.swing = false;
}
window.requestAnimationFrame(playGame);
}
}
**链接至JS完整项目**
https://jsfiddle.net/mugs17/sud2ojxy/17/
最佳答案
您的逻辑在setTimeout中是向后的。您想自动将swing设置为true(这将阻止执行if语句),并在setTimeout回调内部将其重新设置为false。
-这是解决方案:
let player = {
swing: false
}
--
function pressOn(e) {
e.preventDefault();
let tempKey = (e.key == " ") ? "space" : e.key;
keys[tempKey] = true;
if (keys['x'] && player.swing == false) {
player.plane.style.backgroundImage = 'url(guts2.png)';
player.swing = true;
setTimeout(function () {
player.plane.style.backgroundImage = 'url(guts1.png)';
player.swing = false;
}, 1000);
}
关于javascript - 垃圾邮件异步回调打破了我的setTimeout延迟,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58209405/