gpt4 book ai didi

javascript - p5.j​​s - random()、高度和宽度未定义?

转载 作者:行者123 更新时间:2023-11-30 20:58:10 26 4
gpt4 key购买 nike

我正在尝试使用 p5.js 使球在 Canvas 上弹跳,但似乎 widthheightrandom() 未定义。这是我的所有代码:

function setup() {
createCanvas(640,480);
background(240);
}

var dot = {
x: random(width),
y: random(height),
size: 50,
r: 255,
g: 0,
b: 0,
speedX: 5,
speedY: 5
};

function draw() {
background(240);
fill(dot.r, dot.g, dot.b);
ellipse(dot.x, dot.y, dot.size, dot.size);
if (dot.x >= 615 || dot.x <= 25) { //if the ball is out of screen horizontally
dot.speedX = dot.speedX * -1;
}

if (dot.y >= 465 || dot.y <= 25) { //if the ball is out of screen vertically
dot.speedY = dot.speedY * -1;
}

dot.x = dot.x + dot.speedX;
dot.y = dot.y + dot.speedY;
}

如果我使用 JavaScript 的 Math.random,它工作正常。此外,如果我手动输入宽度和高度作为数字(640 和 480),它工作正常。 p5.j​​s 不应该自动分配 height, width, random 等吗?怎么回事?

最佳答案

之前,您不能使用 P5.js 函数或变量(包括 widthheightrandom())在 setup() 被调用之后。那是因为 P5.js 还没有加载,所以它们没有定义。您必须确保对 P5.js 函数或变量的任何调用都在调用 setup() 之后。

在您的情况下,您直接在顶层定义 dot,这发生在最开始,在 setup() 被调用之前。您可以通过将 console.println() 调用放在您的 dot 定义旁边以及 setup() 函数内来测试这一点。

要解决此问题,请将 dot 的初始化移动到 setup() 函数中:

var dot;

function setup() {
createCanvas(640,480);

dot = {
x: random(width),
y: random(height),
size: 50,
r: 255,
g: 0,
b: 0,
speedX: 5,
speedY: 5
}

background(240);
}

function draw() {
...

您可以在 the P5.js FAQ 中阅读更多相关信息.

关于javascript - p5.j​​s - random()、高度和宽度未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47428208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com