Как создать простой гравитационный движок на javascript - PullRequest
0 голосов
/ 07 февраля 2019

Я пытаюсь сделать простую анимацию в javascript, используя библиотеку P5.js.Я хотел бы, чтобы шар появился на некоторой высоте, а затем позволил ему упасть и отскочить, пока он не остановится.

Я не ищу внешнюю библиотеку, просто 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>

Может кто-нибудь мне помочь?Большое спасибо

Ответы [ 2 ]

0 голосов
/ 07 февраля 2019

Сначала вы должны установить начальную скорость равной 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;

См. Также Прыгающие шарики, изо всех сил пытаясь получить большечем 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>
0 голосов
/ 07 февраля 2019

Это довольно просто, вот рабочий (но грубый) способ сделать это:

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);
};
...