为什么我必须将速度添加到object.position.y + object.height?

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

我的代码确实没有任何问题,我正在观看教程来帮助我学习在画布上制作游戏。我理解它的每一点,但我不明白的一件事是为什么我必须在方程中添加速度?我理解它是物体的速度和方向,但为什么我必须添加它?我花了 8 个小时试图理解它。我认为在我明白原因之前我不能继续学习。 soeone请帮助我...

我审问了 2 个独立的人工智能机器人,但他们所说的对我来说毫无意义,即使我要求他们简化它。

当然这是我的代码:

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvasWidth = 770;
canvasHeight = 650;
canvas.width = canvasWidth;
canvas.height = canvasHeight;

let gravity = 7.4;
class Player{
  constructor(){
this.position = {
  x: 175,
  y: 0
  }
    this.velocity = {
      x: 0,
      y: 0
    }
    this.width = 65;
    this.height = 60;
  }

  draw(){
    ctx.fillStyle = "goldenrod";
    ctx.fillRect(this.position.x, this.position.y, this.width, this.height)
  }
  update(){
    this.draw();
    this.position.y += this.velocity.y;
    
  if(this.position.y + this.height + this.velocity.y <= canvas.height){
    this.velocity.y += gravity;
    }else{this.velocity.y = 0}
    
  }
}
let player = new Player();
player.draw()

function animate(){
  requestAnimationFrame(animate)
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  player.update();
}
animate()

我不明白的代码的具体部分是: this.position.y + this.height + this.velocity.y <= canvas.height

我知道 this.position.y + this.height 是播放器底部的位置,但是如果我已经知道播放器的底部位置,为什么我必须添加速度? 我只有 15 岁,我刚刚开始学习几何哈哈

javascript canvas html5-canvas game-physics physics
1个回答
0
投票

看起来这种情况通常会阻止重力将物体带出界限。这包括前视速度并防止下一帧跳出界限。

但是,在检查中添加速度可能无法阻止这种情况,因为对象可能会在下一帧加速并移动更多。然而,防止 OOB 的一种不太容易出错的方法可能是将检查移到位置更新之上。那么,该条件不需要添加速度。

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