首页 > 解决方案 > 如何使用向量施加不同的力?

问题描述

我正在尝试在 p5.js 中制作一个简单的横向卷轴游戏。据我了解,我需要有向量来模仿现实世界的物理学。我真正需要的只是一种将播放器向下推的力和一种在按下键时使其跳跃的力。我从 youtube 上观看了有关该主题的视频,我很确定我完全按照描述进行了操作,但我得到了不同的结果。我的钥匙并不总是被检测到,而且它们都具有不同的力量。先感谢您。

// This is a part of a player class that I have
update(){
  this.pos.add(this.vel)
  this.vel.add(this.acc)
}

applyForce(force){
  this.vel.add(force)
}

earth(){
  if (this.pos.y > height - 100){
    this.pos.y = height - 100
    this.acc.y *= 0
  }
}

// This is where I detect the pressed key
function keyPressed(){
  let jump = createVector(0,-10)
  player.applyForce(jump)
}

// And then in the draw function i have this
player.applyForce(gravity)
player.earth()

标签: javascriptphysicsp5.js

解决方案


基本问题:

  • applyForce应该将力矢量添加到加速度,而不是速度。
  • 您不应该在 draw 函数中更新物理,而是在update.
  • 在游戏中,跳跃机制通常被实现为脉冲(即速度变化)而不是力。您可以为此添加一个applyImpulse功能。
  • 更新后应始终重置加速度,以免力累积。

修改后的代码:

// move all updates to here
update(){
  this.acc.add(gravity)
  this.pos.add(this.vel)
  this.vel.add(this.acc)

  this.earth()

  this.acc = createVector(0, 0)
}

// add to acceleration, not velocity
applyForce(force){
  this.acc.add(force)
}

// impulse for jumping
applyImpulse(imp){
  this.vel.add(imp)
}

// set vertical *velocity* to zero, not acceleration
earth(){
  if (this.pos.y > height - 100){
    this.pos.y = height - 100
    this.vel.y = 0
  }
}

// apply the impulse to jump
function keyPressed(){
  let jump = createVector(0,-10)
  player.applyImpulse(jump)
}

// no updating in the draw function

推荐阅读