You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

p5.js rect()函数异常:期望数字参数却收到NaN

p5.js rect()函数报错:第二个参数为NaN的排查与修复

错误根源分析

错误提示rect() was expecting Number for the second parameter, received NaN instead说明传入rect的y坐标值变为非数字(NaN),追踪代码可定位到三个核心问题:

  • 未声明变量jump:在gravityControl和gravity函数中直接使用jump变量,但未在全局或函数内声明,会导致变量隐式全局化,引发异常。
  • 变量名拼写错误:gravity()函数中写了vel = gravity;,但定义的重力变量是gravity1,未定义的gravity会让vel变成NaN,后续计算playerY时也会变成NaN,最终传给rect()触发报错。
  • 重复定义函数:存在两个完全相同的gravityControl函数,属于冗余代码,易造成混淆。

修复后的代码

//game control
let level = 0;
//gravity
let minHeight = 375;
let direction = 1;
let vel = 2;
let jumpPower = 10;
let gravity1 = 5;
let onPlatform = false; 
let jump = false; // 新增:显式声明jump变量
//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 = gravity1; // 修正:变量名拼写错误
  } else {
    vel = 0;
  }
}

function mousePressed() {
  fullscreen(true);
}

关键修复点

  • 在全局变量区添加let jump = false;,显式声明变量,避免隐式全局化问题。
  • 将gravity()函数中的vel = gravity;改为vel = gravity1;,修正变量名拼写错误。
  • 删除重复的gravityControl函数,精简代码。

内容的提问来源于stack exchange,提问作者helloworld423

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 22:23:16