javascript - 垃圾邮件异步回调打破了我的 setTimeout 延迟
问题描述
因此,当玩家按下 x 时,我的角色 div 会更改其背景图像,如果角色接触到敌人,则会杀死敌人。这个图像切换是做一个挥剑的模拟动画。
我使用 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 FIDDLE 完整项目的链接**
解决方案
您的逻辑在 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);
}
推荐阅读
- python - 命令行 python 和 jupyter notebooks 使用两个不同版本的 torch
- c# - 不支持网络浏览器
- flutter - 当我从 Flutter 应用程序使用 post 方法向 Web 服务请求时出现意外字符错误
- sql - 三元运算符导致索引处缺少 IN 或 OUT 参数
- html - 需要找到文件源
- reactjs - React Router:子组件中定义的路由不起作用
- laravel - 字体:在生产环境中找不到 404
- c# - 在 Ribbon.cs 中与 VSTO Word 插件上的文件和目录进行交互
- python - 仅包含跨度文本而不是包含特定文本字符串
- python-3.x - 我已经在 Python 上安装了我的 scikit-image