Search code examples
javascripthtml5-canvasparticles

Particles won't accelerate?


I'm trying to make particles that accelerate using JavaScript and the HTML5 Canvas, but I cannot get them to accelerate, they just move at a constant speed. Does anyone know why?

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

Solution

  • Your draw function is using the yVel passed to the constructor. try with this.y += this.yVel;