使物体以逼真的重力跳跃一次

Making an object jump once with realistic gravity

我想让我的物体(此时是一个矩形)跳一次,在上升的过程中失去速度。当它快要停下来时,我希望它掉头并在下降的过程中加速。当它再次撞到地面时,它应该停下来。当我再次按下 Key 时,它应该再次执行相同的操作。


我尝试编写的代码实现了一个变量 float gravity = 0.75; 和一个跟踪速度的变量 float speed = 10;


当速度大于1时,速度应该减去矩形的Y坐标,然后速度应该变低,因为我将它与小于1的重力相乘

else if (keyCode == UP|| key == 'w') {
    while (speed >1 ) { 
      playerYPosition = playerYPosition-speed;
      speed = speed * gravity;
    }

Gravity 大于 1 但为负,因此我减去的数字在最终结果中相加,矩形变小。要获得速度,速度会乘以重力。

    gravity = -1.25;
    speed = speed * gravity;
    playerYPosition = playerYPosition-speed;

速度现在应该在 -1.2 左右...,所以它小于 -1,这 while(...) 应该可以。同样,它应该随着时间的推移增加速度,直到达到起始速度,刚好是负的,并且是起始点。

while (speed < -1 && speed > -10) {
      playerYPosition = playerYPosition-speed;
      speed = speed * gravity;

然后重力应该再次变为 0.75,速度变为 10。

gravity = 0.75;
speed = 10;

所以矩形并没有那样做,而是不断向上跳(我认为)10 像素,仅此而已。

这是整个代码块,需要重读:

float gravity = 0.75;
float speed = 10;

else if (keyCode == UP|| key == 'w') {
    while (speed >1 ) { 
      playerYPosition = playerYPosition-speed;
      speed = speed * gravity;
    }
    gravity = -1.25;
    speed = speed * gravity;
    playerYPosition = playerYPosition-speed;
    
    while (speed < -1 && speed > -10) {
      playerYPosition = playerYPosition-speed;
      speed = speed * gravity;
    }
    gravity = 0.75;
    speed = 10;

如果您使用 while 循环来计算您的 Y 位置,您将无法可视化您的跳跃模拟,因为所有数学运算都将在一个帧中计算。 要进行基于物理的跳跃模拟,您需要有一个代表地面的变量(这是您的初始 Y 变量),此外,一旦您的玩家点击,您需要为速度变量提供您的全速,然后每一帧都会降低它如果您还没有到达地面,则在检查每一帧时根据您的重力。 这是我写的一个例子来证明,我试着保留你的变量名:

final float gravity = 0.5; 
final float jmp_speed = 10; //the speed which the square is going to jump
float speed = 0; //the actual speed every frame
final float ystart = 280; //the initial Y position ( which also represent the Y of the ground )
float playerYPosition = ystart; //give the player the Y of the ground on start

void setup(){
  size(300,300);
}

void keyPressed() {
    //also check that the player is on ground before jumping
   if( (keyCode == UP || key == 'w') && (playerYPosition == ystart) ) 
    {
      speed=-jmp_speed; //when the player press jump and he is on ground we give speed the max value
    }
}

void draw(){

    background(150);
    rect(150,playerYPosition,10,10);

    //this code will be executed every frame
    //check if the player Y position won't hit the ground if we increment it by speed
      if(playerYPosition+speed < ystart)
      {
        playerYPosition+=speed;
        speed+=gravity; //increment speed by gravity ( will make speed value go from negative to positive slowly)
      }
      else
      {
        //if the player is gonna hit the ground the next frame

        playerYPosition = ystart; // put back the player on ground
        speed=0; // make the speed 0
      }  
}