我正在尝试在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()
答案 0 :(得分:1)
基本问题:
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