2016-05-12 56 views
1

我試圖製作使用JavaScript和HTML5 Canvas加速的粒子,但我無法讓它們加速,它們只是以恆定的速度移動。有誰知道爲什麼?粒子不會加速?

document.addEventListener("DOMContentLoaded", init); 
function init() { 
    canvas = document.getElementById("canvas"); 
    ctx = canvas.getContext("2d"); 
    angle = Math.random() * (2 * Math.PI); 

    pArray = []; 
    for (i = 0; i<25; i++) { 
     angle = Math.random() * (2*Math.PI); 
     pArray[i] = new Particle(Math.cos(angle), Math.sin(angle)); 
    } 
    setInterval(loop, 50); 
} 
function loop() { 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    for (x = 0; x < pArray.length; x++) { 
     pArray[x].draw(); 
    } 
} 
function Particle(xVel, yVel) { 
    this.xVel = xVel; 
    this.yVel = yVel; 
    this.x = canvas.width/2; 
    this.y = canvas.height/2; 

    this.draw = function() { 
     this.x += xVel; 
     this.y -= yVel; 
     this.yVel += 1; 

     ctx.beginPath(); 
     ctx.arc(this.x, this.y, 1, 0, Math.PI * 2); 
     ctx.fillStyle = "rgb(0, 255, 0)"; 
     ctx.fill(); 
    } 
} 

回答

3

您的繪圖函數使用傳遞給構造函數的yVel。 嘗試this.y += this.yVel;

+0

哎呦哈哈謝謝 –

2

看起來你的繪圖函數使用的是構造函數中的xVel和yVel而不是粒子實例。嘗試將this.y += yVel更改爲this.y += this.yVel

0

您可以創建額外的變量名稱爲速度,然後加速這樣的球:

function Particle(xVel, yVel) { 
    this.xVel = xVel; 
    this.yVel = yVel; 
    this.speed = 1; 
    this.x = canvas.width/2; 
    this.y = canvas.height/2; 

    this.draw = function() { 
     this.x += this.speed * this.xVel; 
     this.y += this.speed * this.yVel; 
     this.speed++; 

     ctx.beginPath(); 
     ctx.arc(this.x, this.y, 1, 0, Math.PI * 2); 
     ctx.fillStyle = "rgb(0, 255, 0)"; 
     ctx.fill(); 
    } 
} 

這裏是例如在的jsfiddle https://jsfiddle.net/3nnm2omm/