如何在JavaScript上创建一个简单的重力引擎

3

我想使用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>

有人可以帮我吗?非常感谢。


你可以阅读相关的w3schools教程 - FZs
2个回答

2

首先您需要将起始速度设置为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》,其中有关于如何处理超过一个球的建议。

请看下面的示例,我在您的原始代码上应用了这些建议:

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>

Demo


0

这很简单,以下是一种可行(但粗糙)的方法:

var velY = 0;
var yPos = 0;
draw = function() {
velY += 0.1;//Make this value higher for stronger gravity.
yPos += velY;

if (yPos > 400) {
velY = -velY;
yPos = 400;
}//This may need a little tweaking.

ellipse(300, yPos, this.diameter);
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接