2016-05-12 13 views
1

Ich versuche Partikel herzustellen, die mit JavaScript und HTML5 Canvas beschleunigen, aber ich kann sie nicht beschleunigen, sie bewegen sich nur mit konstanter Geschwindigkeit. Weiß jemand warum?Partikel werden nicht beschleunigen?

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

Antwort

3

Ihre Zeichenfunktion verwendet den , der an den Konstruktor übergeben wird. versuchen mit this.y += this.yVel;

+0

hoppla haha ​​danke –

2

Es sieht aus wie Ihre Zeichenfunktion der XVel und Yvel vom Konstruktor statt von dem Partikel Instanz verwendet. Versuchen Sie, this.y += yVel zu this.y += this.yVel zu ändern.

0

können Sie zusätzliche Variable erstellen mit dem Namen Geschwindigkeit und dann diese die Kugeln wie beschleunigen:

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

Hier ist beispielsweise auf jsfiddle https://jsfiddle.net/3nnm2omm/