由于某种原因我无法调用 setup()

I can't call setup() for some reason

我无法在我的 p5js 项目上调用 setup() 或在项目启动后将任何布尔值更改为 false。

我试过创建一个名为 reset() 的新函数,我没有调用 setup(),而是调用了 reset(),但没有成功。

let x, y;
let start;
let trianglespeed;
let x1, y1, x2, y2, x3, y3;
let r;
let lost, playing, win;

function setup() {
  createCanvas(400, 400);
  r = random(900, 4000);
  x = 100 - 20;
  y = 200 - 20;
  x1 = r
  y1 = 150;
  x2 = x1 + 10;
  y2 = 180;
  x3 = x2 + 10;
  y3 = 150;
  textSize(30);
  noStroke();
  start = "Click screen to play";
  trianglespeed = 0;
  lost = false;
  playing = false;
  win = false;
}

function draw() {
  background(220);
  fill(112, 166, 255);
  text(start, 70, 100);
  fill(178, 178, 178);
  rect(x, y, 20, 20);
  fill(255, 99, 99);
  triangle(x1, y1, x2, y2, x3, y3);
  console.log(mouseX);
  x1 = x1 + trianglespeed;
  x2 = x2 + trianglespeed;
  x3 = x3 + trianglespeed;
  if (playing == true) {
    if (x1 <= 70) {
      trianglespeed = 0;
      start = "Press R to restart";
      x1 = x1;
      x2 = x1 + 10;
      x3 = x1 + 20;
      lost = true;
    }
  }
  console.log(playing, lost, win);
}

function mousePressed() {
  if (lost == false) {
    start = "";
    trianglespeed = -10;
    playing = true;
  }
  if (playing == true) {
    if (x2 >= 80 && x2 <= 100) {
      start = "you win, press R to restart";
      trianglespeed = 0;
      x1 = x1;
      x2 = x1 + 10;
      x3 = x1 + 20;
      win = true;
    }
  }
}

function KeyPressed() {
  if (keyCode == R) {
    setup();

//the problem ^^^
  }
}

我希望在我按下 R 后整个事情会重新开始,但它没有。

告诉我我做错了什么。

p5.js 说:

The setup() function is called once when the program starts. It's used to define initial environment properties such as screen size and background color and to load media such as images and fonts as the program starts. There can only be one setup() function for each program and it shouldn't be called again after its initial execution.

并有一张便条

Note: Variables declared within setup() are not accessible within other functions, including draw().

这意味着您不能使用 setup 函数来重置值,因为它用于代码的初始化。

可以看官网:https://p5js.org/reference/#/p5/setup

如果您想更改某些值,您可以使用另一个函数来处理您的代码。

问题是这个

function KeyPressed() {
  if (key == "r") {
    reset();

  }
}

按键功能上的 K 是大写字母 K,不是正常字母。