如何使用矢量施加不同的力?
How do can i apply different forces using vectors?
我正在尝试在 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()
基本问题:
applyForce
应该将力矢量添加到 加速度 ,而不是速度。
- 您不应该在绘图函数中更新物理,但在
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
我正在尝试在 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()
基本问题:
applyForce
应该将力矢量添加到 加速度 ,而不是速度。- 您不应该在绘图函数中更新物理,但在
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