javascript - 如何在 javascript 上创建一个简单的重力引擎
问题描述
我正在尝试使用 P5.js 库在 javascript 中制作一个简单的动画。我想让一个球出现在某个高度,然后让它掉下来,让它弹跳直到它停下来。
我不是在寻找外部库,只是 P5。
我的代码是这样的:
function Ball() {
this.diameter = 50;
this.v_speed = 5;
this.ypos = height/2 - 100;
this.xpos = width/2;
this.update = function(){
this.ypos = this.ypos + this.v_speed;
this.ypos = constrain(this.ypos, this.diameter/2, height-this.diameter/2);
}
this.show = function(){
ellipse(this.xpos, this.ypos, this.diameter);
fill(255);
}
}
var ball;
function setup() {
createCanvas(600, 600);
ball = new Ball();
}
function draw() {
background(0);
ball.update();
ball.show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
有人能帮我吗?非常感谢
解决方案
首先,您必须将起始速度设置为 0 并定义重力:
this.v_speed = 0;
this.gravity = 0.2;
update
可以直接应用于您的示例的工作方法如下所示:
this.starty = height/2 - 100;
this.endy = height-this.diameter/2;
this.update = function(){
this.v_speed = this.v_speed + this.gravity;
this.ypos = this.ypos + this.v_speed;
if (this.ypos >= this.endy){
this.ypos = this.endy;
this.v_speed *= -1.0; // change direction
this.v_speed = this.v_speed*0.9;
if ( Math.abs(this.v_speed) < 0.5 ) {
this.ypos = this.starty;
}
}
}
关键是在球在地面反弹时降低速度并改变方向:
this.v_speed *= -1.0;
this.v_speed = this.v_speed*0.9;
另请参阅Bouncing Balls,努力获得超过 1 个(处理)。
请参阅示例,其中我将建议应用于您的原始代码:
function Ball() {
this.diameter = 50;
this.v_speed = 0;
this.gravity = 0.2;
this.starty = height/2 - 100;
this.endy = height-this.diameter/2;
this.ypos = this.starty;
this.xpos = width/2;
this.update = function(){
this.v_speed = this.v_speed + this.gravity;
this.ypos = this.ypos + this.v_speed;
if (this.ypos >= this.endy){
this.ypos = this.endy;
this.v_speed *= -1.0; // change direction
this.v_speed = this.v_speed*0.9;
if ( Math.abs(this.v_speed) < 0.5 ) {
this.ypos = this.starty;
}
}
}
this.show = function(){
ellipse(this.xpos, this.ypos, this.diameter);
fill(255);
}
}
var ball;
function setup() {
createCanvas(600, 600);
ball = new Ball();
}
function draw() {
background(0);
ball.update();
ball.show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
推荐阅读
- python - 为什么 pyrlp.Serializable 类不允许在初始化后编辑属性?如何才能做到这一点?
- javascript - 如何在 Electron 中删除 DOM 元素
- swift - 为什么我的 TableViewController 只返回一个可折叠部分?
- sql - 为什么要评估带有不可能的 CASE 语句的查询?
- python - Pandas 的多线程问题
- java - JDA - 如何将“成员”对象转换为“用户”对象,反之亦然?
- reactjs - Prismic & ReactJS:如何查询 Single 类型内的文档
- c# - 如何使用 Cinchoo ETL 的 ChoCSVWriter 写入数组的所有值?
- chromium - 如何解决内网环境中出现两条 Chromium 浏览器报错信息?
- delphi - 为什么 Windows 上的 Delphi FireMonkey 应用程序无法与 Microsoft Teams 正确共享?