如何在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;

可以直接应用于您的示例的有效更新方法如下所示:

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,struggling with getting more than 1 (processing).

请参见示例,其中我将建议应用于原始代码

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.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>

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...