如何使用 p5.js 让我的火柴人跳跃?

How can I make my stickfigure jump using p5.js?

我刚刚在学校学习 JavaScript,我们需要为一项作业制作游戏。我开始画我的主角,让他左右走动。现在,我想让我的主角在每次按下空格键时跳跃。因为我很新,在网上找不到任何东西,所以我想我可以在这里拍摄。这是我目前所拥有的:

chX = 100;
chY = 250;

function setup() {
    createCanvas(800,400);
  }
  
  function draw() {
    background("#0c3c5e");
    noStroke();
    fill("#466D1D");
    rect(0,300,800,100);
    mainCharacter(chX,chY);
    if(keyDown('LEFT_ARROW')){
        chX = chX - 1;
    }
    if(keyDown('RIGHT_ARROW')){
        chX = chX + 1;
    }

    
  }

  function mainCharacter(chX, chY){

    fill(255);
    stroke(0);
    rectMode(CENTER);
    rect(chX, chY + 49, 20, 50); //lichaam
    circle(chX, chY, 50); //hoofd
    line(chX - 30, chY + 20, chX - 10, chY + 40); //arm links
    line(chX + 10, chY + 40, chX + 30, chY + 20); //arm rechts
    line(chX - 10, chY + 75, chX - 10, chY + 115); //been links
    line(chX - 10, chY + 75, chX - 10, chY + 115); //been rechts
    line(chX + 10, chY + 75, chX + 10, chY + 115); //been rechts
    strokeWeight(5);
    point(chX - 10, chY);
    point(chX + 10, chY);
  } 

谁能解释一下我如何让 'mainCharacter' 跳跃?还是对带有一些解释的网站的引用?提前致谢!

好吧,这可能是最简单的方法:数字基本上是随机的,而且这是一个圆圈,因为它更容易一些

let x = 300, y = 200, groundY = 300
let yVel = 0, gravity = 5

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

function draw() {
  background(20);
  
  if(y + 10 <= 300){ // if player.y + player.height < ground (if player is in the air)
    y += gravity     //                      radius*
  }
  
  y += yVel // y velocity
  yVel /= 1.2
  
  
  strokeWeight(16); stroke('lime')
  point(x, y)                        // the player
  
  strokeWeight(4); stroke('gold')
  line(0, groundY, width, groundY)   // the ground
}


function keyPressed(){ // only once on press of space bar (space bar in ascii is 32)
  if(y + 10 >= 300)
    if(keyCode == 32) // you could use && here
      yVel = -25
}


一跳基本上就是:

  • 检查 space 条是否被按下

  • 检查玩家是否在空中

  • 给玩家一些向上的速度*“向下”这里*

  • 如果玩家还在空中

  • 继续施加重力

  • 不断降低玩家的速度

你也可以做加速让一切更流畅,但是代码有点多,sooooooo,应该只是:

position += velocity
velocity += acceleration