p5.js: keyIsPressed 未定义

p5.js: keyIsPressed is not defined

我正在尝试检查 draw() 函数中的键盘事件,因为我必须同步修改全局变量(因此我不能简单地将我的键盘事件代码放在单独的 keyTyped() 函数)。问题是当我在 draw() 函数中使用变量 keyIsPressed 时,出现以下错误:

Uncaught ReferenceError: keyIsPressed is not defined

下面是我的代码:

var myp25;

var mazeDisplay = function(p) {
    p.setup = function() {
        var canvas = p.createCanvas(400, 400);
        p.background("#ff3056");
    }

    p.draw = function() {
        if (keyIsPressed === true) {
            console.log("key pressed.");
        }
    }
};

myp25 = new p5(mazeDisplay, "canvas2-wrapper")

但我正在关注 keyIsPressed 变量的实现,如此 link 所示:https://p5js.org/reference/#/p5/keyIsPressed

您正在使用 instance mode,因此每个 P5.js 函数和变量都必须使用您对草图的引用。在您的情况下,这是您的 p 变量。

if (p.keyIsPressed === true) {

therefore I can't simply put my code for keyboard events in a separate keyTyped() function

可以,你只需要使用 p 变量即可。

p.keyTyped = function() {
  // whatever
}