簡體   English   中英

如何在javascript上創建一個簡單的重力引擎

[英]How to create a simple gravity engine on 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> 

這很簡單,這是一種工作(但粗略)的方式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM