javascript - 如何在 javascript 画布中为不同的事物重用相同的密钥?
问题描述
在画布中,我希望能够使用回车键做一件事,然后再次按下它来做另一件事。
例如,
if(enterPressed) {
// do one thing
}
if (enterPressed) {
//Do some other thing
}
问题是当我按下回车键时,它会自动同时执行这两项操作,而我希望它希望它分别执行每个语句。
对于更多上下文,我想做的类似于口袋妖怪游戏中的文本样式,其中游戏将显示一些文本,然后等到您按下按钮然后显示下一组文本。
解决方案
问题中的示例代码连续有两个语句,我假设这是您想要处理的方式enterPressed
要进行第二个(或第三个或更多)操作,您需要存储输入操作的状态。例如,这是第一次印刷吗?
// this in the setup code.
var enterAction = "firstPress"
然后每次enterPressed
处理时,您还必须检查状态,以便发生正确的操作。
if (enterPressed && enterAction === "firstPress") {
当您处理该操作时,您还设置了要处理的下一个状态。因为您连续有两个语句都检查是否enterPressed
为真,所以您还需要表明您已经处理了新闻。这可以只是设置enterPressed = false
enterAction = "secondPress";
enterPressed = false;
}
因此你的代码看起来像
// Init the first enter state
const FIRST = 1, SECOND = 2;
var enterAction = FIRST;
并将问题代码替换为
// Handling first press
if (enterPressed && enterAction === FIRST) {
enterAction = SECOND; // set action for next press
enterPressed = false; // clear press to indicate its been handled
// do one thing
}
// Handling second press
if (enterPressed && enterAction === SECOND) {
enterAction = FIRST; // set action for next press
enterPressed = false; // clear press to indicate its been handled
//Do some other thing
}
推荐阅读
- function - 如何将多个域和本地用户帐户传递给函数
- sql - oracle sql中的号码检查
- javascript - 如何将整个 JSON 响应转换为值数组
- java - 当条件满足时,while循环不会终止
- c# - 如何在 Unity3D 中添加回避和追逐行为
- javascript - 停止一个绝对 div 溢出父级
- npm - 如何使用 package-lock.json 中的版本覆盖 package.json “最新” dist-tag?
- sql - 子查询中的 PostGreSql ISNULL 或 Coalesce
- typescript - 如何在 TypeScript 3.0 中使用项目引用?
- html - 悬停时显示 div