在实施重力和地面 y 变量的同时,我将如何进行 gif 跳跃?

How would I make a gif jump, while implementing gravity and a ground y-variable?

CatBus Code Link

我正在尝试让我的 gif “跳跃”,同时还以 730 的 y 值返回静止状态。不多也不少。当 wifi 断开时,它的工作程度与恐龙游戏相同。我也想包括一个重力函数。我不知道该怎么做。 (我对编码很陌生。)有什么建议吗?

[代码如下]

let img;    //background
var bgImg;    //also the background
var x1 = 0;
var x2;

var scrollSpeed = 4;  //how fast background is

let bing;   //for music

let cat = {   //coordinates for catbus
  x:70,
  y:730
}
  
var mode;  //determines whether the game has started


function preload() {
  bgImg = loadImage("backgwound.png");  //importing background

  bing=loadSound('catbus theme song.mp3');  //importing music

}

function setup() {
  createCanvas(1000, 1000);   //canvas size

  img = loadImage("backgwound.png"); //background in

  x2 = width;

bing.loop()  //loops the music
  
  catGif=createImg("catgif.gif")    //creates catbus
  catGif. position(cat.x, cat.y)    //creates position
  catGif. size(270,100)             //creates how big
  
  mode = 0;                         //game start
  textSize(50);                     //text size
  
}

function draw() {

  let time = frameCount;        //start background loop

  image(img, 0 - time, 0);

  image(bgImg, x1, 2, width, height);
  image(bgImg, x2, 2, width, height);

  x1 -= scrollSpeed;
  x2 -= scrollSpeed;

  if (x1 <= -width) {
    x1 = width;
  }
  if (x2 <= -width) {
    x2 = width;
  }                       //end background loop

  
  fill("white")              //text colour
 if(mode==0){ 
  text('Press SPACE to start the game.',150,500);     //what text to type
 }  

  if(mode==0){
  text('CATBUS BIZZARE ADVENTURE',135,450)    //what text to type
  
  }
    
}


function pickRandom() {
  x = random(20, width - 20);
}

我已经更新了您的 p5.js sketch 以指明正确的方向。

我已经介绍了一些变量,这些变量是在设置之前在您的代码顶部定义的:

let gravity = 0.1;
let velocity = 0;
let upForce = 3;

let startY = 730;
let startX = 70;
...

您可以调整这些数字以适合您的游戏。但这里的基本前提是每一帧我们将速度添加到 cat.y 并且 velocity 每帧增加 gravity:

 cat.y = cat.y + velocity;
 velocity = velocity + gravity;

但是,有一个警告,如果猫在 startY,我们不想将速度添加到 cat.y,因为 startY 是草:

if (cat.y > startY) {
  velocity = 0;
  cat.y = startY;
}

catGif.position(cat.x, cat.y); // reposition the gif

最后,当你按下空格键时,跳! (并去掉开始屏幕)

function keyPressed() {
  if (keyCode === 32) {
    //spacebar
    mode = 1;
    velocity -= upForce;
  }
}