Connor O'Hara
Connor O'Hara

Reputation: 139

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

Upvotes: 1

Views: 74

Answers (3)

vegazz
vegazz

Reputation: 1441

You can create extra variable with name speed and then speed up the balls like this:

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

Here is example on jsfiddle https://jsfiddle.net/3nnm2omm/

Upvotes: 0

Flint
Flint

Reputation: 1691

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

Upvotes: 3

Shaun
Shaun

Reputation: 625

It looks like your draw function is using the xVel and yVel from the constructor instead of from the particle instance. Try changing this.y += yVel to this.y += this.yVel.

Upvotes: 2

Related Questions