javascript - 如何使用向量施加不同的力?
问题描述
我正在尝试在 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
应该将力矢量添加到加速度,而不是速度。- 您不应该在 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
推荐阅读
- c++ - 对于大于 0x1FFF 的卷扇区,Windows FileWrite 失败
- node.js - 如何使用带有许多请求的 Node mssql 修复“无法连接(序列)”
- kubernetes - 对于 Kubernetes 中的部署/升级后测试,测试的最佳触发器是什么
- regex - Ansible:lineinfile 不断压缩我现有的行而不是向其附加文本
- django - 防止 django 管理员更改创建 LogEntry
- java - NavigationDrawerActivity 与 BottomNavigationActivity
- python - 用一行上的某些字段格式化一些 JSON 对象?
- rust - 是否可以将元组结构构造函数传递给函数以返回不同类型的值?
- powershell - Ansible:如何处理 win_shell 变量的引号
- python - 检查给定的 wiki 页面是否存在