P5.JS 抛出关于我的矩形的错误

问题描述 投票:0回答:1

错误是这样的: p5.js 说:[sketch.js,第 63 行] rect() 期望第二个参数为 Number,但收到的是 NaN。 这是我的代码:

//game control ***(not used rn)***
let level = 0;
//gravity
let minHeight = 375;
let direction = 1;
let vel = 2;
let jumpPower = 10;
let gravity1 = 5;
let onPlatform = false; 
//player setup and whatnot
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 和 javascript 的新手

javascript p5.js
1个回答
0
投票

gravity
函数中,您执行
vel = gravity
(第 107 行或附近),即将函数本身分配给变量
vel
(应该是一个数字),这意味着当您执行

playerY = playerY + direction * vel;

在下一帧,您将向

playerY
分配 NaN:

console.log(5 + 3 * function() {});

这反过来又破坏了其余的。

想必您想要

vel = gravity1

我建议用动词命名你的函数,例如

computeGravity()
handleMovement()
,以及带有名词的变量。

© www.soinside.com 2019 - 2024. All rights reserved.