OignonDoux
OignonDoux

Reputation: 13

Bouncing ball in Canvas

I'm trying to make a ball bounce inside a canvas and it doesn't work. The ball is getting stuck against the "walls" and I don't understand why. Anyone know how I can fix this?

var can = document.querySelector("canvas");
var ctx = can.getContext("2d");

var canvasWidth = 500;
var canvasHeight = 400;

var radius = 30;
var pX = 60;
var pY = 50;

function draw() {
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.beginPath();
    ctx.fillStyle = "red";
    ctx.arc(pX, pY, radius, 0, Math.PI * 2, false);
    ctx.fill();
    ctx.closePath();
}


function animate() {

    var vX = 3;
    var vY = 3;

    if (pY >= canvasHeight - radius) {
        vY = -vY;
    }


    if (pX >= canvasWidth - radius) {
        vX = -vX;
    }

    pX += vX;
    pY += vY;

    draw();
    requestAnimationFrame(animate);
}

animate();

Upvotes: 1

Views: 1358

Answers (1)

boxsome
boxsome

Reputation: 178

Your conditions for collision detection only consider the bottom wall and the right-side wall. You need to add conditions for the top wall and the left-side wall. Something like

if (pY >= canvasHeight - radius || pY <= radius) {
    vY = -vY;
}


if (pX >= canvasWidth - radius || pX <= radius) {
    vX = -vX;
}

You are seeing the strange behaviour with your collision detection because vX and vY are locally declared and initialized in animate. This means, every time animate is called, it will be re-initialized.

Simply move vX and vY declarations out of the animate function.

EDIT: JsFiddle if you want to see it in action: http://jsfiddle.net/y45fhko7/

Upvotes: 2

Related Questions