我的 p5.js
rect()
函数出现错误。我已经阅读了他们的函数文档,并且我相信我已经正确使用了该函数。我收到的错误是:
[sketch.js, line 63] rect() was expecting Number for the second parameter, received NaN instead.
这是我遇到错误的代码:
//game control
let level = 0;
//gravity
let minHeight = 375;
let direction = 1;
let vel = 2;
let jumpPower = 10;
let gravity1 = 5;
let onPlatform = false;
//player setup
let playerX = 400;
let playerY = 370;
let playerWidth = 30;
let playerHeight = 70;
//platform
let platX = 200;
let platY = 300;
let platWidth = 200;
let platHeight = 40;
function setup() {
createCanvas(800, 500);
rectMode(CENTER);
textAlign(CENTER);
}
function gravityControl() {
if (keyIsDown(32)) {
jump = true;
} else {
jump = false;
}
}
function draw() {
background(220);
movement();
gravityControl();
gravity();
if (level == 0) {
game();
}
}
function game() {
background(150, 230, 240);
//floor
noStroke();
fill(0, 255, 0);
rect(width / 2, 450, width, 100);
//platform
stroke(0);
strokeWeight(4);
fill(218, 218, 138);
rect(platX, platY, platWidth, platHeight);
//player
noStroke();
fill(255, 0, 0);
rect(playerX, playerY, playerWidth, playerHeight);
onPlatform = false;
if (playerX >= platX - platWidth / 2 && playerX <= platX + platWidth / 2) {
if (playerY - playerHeight / 2 >= platY - platHeight / 2) {
playerY = constrain(
playerY,
platY + platHeight / 2 + playerHeight / 2,
height
);
}
else if (playerY + playerHeight / 2 <= platY + platHeight / 2) {
playerY = constrain(
playerY,
0,
platY - platHeight / 2 - playerHeight / 2
);
if (playerY + playerHeight / 2 >= platY - platHeight / 2) {
onPlatform = true;
}
}
}
}
function movement() {
if (keyIsDown(LEFT_ARROW)) {
playerX -= 5;
}
if (keyIsDown(RIGHT_ARROW)) {
playerX += 5;
}
}
function gravity() {
if (playerY >= minHeight && jump == false) {
if (playerY > minHeight) {
playerY = minHeight;
}
} else {
playerY = playerY + direction * vel;
}
if (jump == true) {
vel = -jumpPower;
} else if (!onPlatform) {
vel = gravity;
} else {
vel = 0;
}
}
function gravityControl() {
if (keyIsDown(32)) {
jump = true;
} else {
jump = false;
}
}
function mousePressed() {
fullscreen(true);
}
我不知道会发生什么,它曾经对我有用,但突然间,它给了我这个错误。如果您回答,请记住我是 p5.js 和一般 JavaScript 编程语言的新手。
在
gravity
函数中,您执行 vel = gravity
(第 107 行或附近),即将函数本身分配给变量 vel
(应该是一个数字),这意味着当您执行
playerY = playerY + direction * vel;
在下一帧,您将向
playerY
分配 NaN:
console.log(5 + 3 * function() {});
这反过来又破坏了其余的。
想必您想要
vel = gravity1
。
我建议用动词命名你的函数,例如
computeGravity()
、handleMovement()
,以及带名词的变量。
正如@AKX所说,您将速度分配给函数
gravity
。您尚未使 gravity
函数返回任何内容,因此您将 undefined
分配给 vel
变量,当使用该值绘制矩形时,该变量将不兼容,因为 rect(x, y, w, h)
接受 number
数据类型,因此它告诉您给定的值是 NaN(不是数字)。
我还注意到你定义了
gravityControl
两次。不需要定义两次,特别是当两个定义包含相同的代码时。我也不建议同时使用 gravity
和 gravityControl
函数,因为它们可以组合成同一个函数,比如 handleGravity
。
此外,
gravityControl
的名称具有误导性,因为它不是控制重力,而是接受切换jump
布尔值的按键输入。可以将其放入 keyPressed
函数中,而不是作为每帧运行的单独函数。