【问题标题】:My p5.js code is sometimes lagging and idont know how?我的 p5.js 代码有时会滞后,我不知道怎么办?
【发布时间】:2022-01-11 00:05:01
【问题描述】:

我是 p5.js 的初学者,我正在尝试制作一个接球游戏,球从天上掉下来,你用篮子接住它们,但是当你运行代码时,有时球不会掉下来直到等待几秒钟并移动篮子,谁能告诉我这是为什么?

这是我的代码:

let speed = 3;
let x = 300;
let y = 0;
let score = 0;

function setup() {
  createCanvas(600, 400);
}

function draw() {
  background(0);
  ellipse(x, y, 20, 20);
  y = y + speed;
  rect(mouseX, height - 10, 60, 40);
  fill(255);
  text("score = " + score, 30, 20);

  if (y > height - 10 && x > mouseX - 20 && x < mouseX + 20) {
    y = -20;
    speed += 1;
    score += 1;
  }
  if (y == -20) {
    x = random(width);
  }
}
function reset(){
  score = 0;
  speed = 2;
  y = -20;
}

【问题讨论】:

  • 在 StackOverflow 上提问时,您应该包含您的代码,最好是 Runnable Snippet,而不是链接到外部网站。

标签: javascript game-physics p5.js


【解决方案1】:

你的游戏逻辑好像有点奇怪:

你每增加一帧y 的速度。您检查的每一帧 y 值是否已通过桨位置 (height - 10) 并且在桨的区域内(尽管这方面的数学有点偏离)。但是,对于球何时离开屏幕边缘并错过球拍,您没有任何条件。因此,一旦球离开屏幕,直到玩家将球拍移动到它可以接住球的位置,什么都不会发生。

这是一个固定版本:

let speed = 2;
let x = 300;
let y = 0;
let score = 0;
let coolDown = 0;

function setup() {
  createCanvas(windowWidth, windowHeight);
  x = width / 2;
}

function draw() {
  if (coolDown > 0) {
    background('red');
  } else {
    background(0);
    ellipse(x, y, 20, 20);
    y = y + speed;
  }
  rect(mouseX - 20, height - 10, 40, 10);
  fill(255);
  text("score = " + score, 30, 20);
  // After the player misses give them a second
  if (coolDown > 0) {
    coolDown--;
    return;
  }
  if (y > height - 10 && x > mouseX - 20 && x < mouseX + 20) {
    y = -20;
    speed += 0.5;
    score += 1;
  } else if (y > height) {
    // The ball is off screen
    coolDown = 30;
    y = -20;
    score -= 1;
  }
  if (y == -20) {
    x = random(width);
  }
}
function reset() {
  score = 0;
  speed = 2;
  y = -20;
}
html, body {
margin: 0;
padding: 0;
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"&gt;&lt;/script&gt;

需要注意的另一件事是,如果您将鼠标移到窗口或 iframe 之外,那么 p5.js 将不会更新 mouseXmouseY 位置。为防止这种情况发生,您可以考虑使用requestPointerLock

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2021-06-21
    • 1970-01-01
    • 2016-11-25
    • 2011-12-13
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多