繁体   English   中英

如何在javascript画布中为不同的东西重用相同的键?

[英]How can I reuse the same key for different things in javascript canvas?

在画布中,我希望能够使用回车键做一件事,然后再次按下它来做另一件事。

例如,

if(enterPressed) {

   // do one thing


}

if (enterPressed) {

    //Do some other thing


}

问题是当我按下回车键时,它会自动同时执行两件事,而我希望它分别执行每个语句。

对于更多上下文,我想要做的类似于 pokemon 游戏中的文本样式,游戏将显示一些文本,然后等到您按下按钮,然后显示下一组文本。

您的问题并非特定于 JavaScript 或 Canvas,而是更多地与通用编程技术相关。 您所描述的是程序的不同状态,而不是作为对事件的反应而完成的 2 个操作。

因此,认为您的程序由多个状态组成: Displayed first text to user -> Displayed second text to user

您将根据用户采取的某些操作在这些状态之间切换,在您的情况下,当他们按下 Enter 键时。 有很多方法可以保存程序状态并在这些状态之间切换,但我可以举出的最简单的方法之一是,将文本保存在一个数组中,并使用一个索引值来保存哪个是当前索引:

var currentIndex = 0;
var texts = ["This is first message", "This is second message"]
if (enterPressed) {
    //you need to have boundary checks of course, skipping for simplicity
    displayText(texts[currentIndex])
    currentIndex++;
}

这是保持程序状态并根据用户操作在这些状态之间切换的一种方法。

问题中的示例代码在一行中有两个语句,我认为这是您要如何处理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
}    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM