2

I'm trying to get collision detection and handling working in JavaScript using two balls at the moment. I can detect when the balls collide with the boundary of the canvas and can get them to bounce back and I can tell when the balls collide with eachother but I can't get them to bounce off eachother properly.

What I have at the moment:

$(document).ready(function() {
    var canvas = $("#myCanvas");
    var context = canvas.get(0).getContext("2d");
    var canvasWidth = canvas.width();
    var canvasHeight = canvas.height();
    ball1 = new Ball(30),
    ball2 = new Ball(30),
    angle1 = 25,
    angle2 = 47,
    speed = 3,
    ball1.x = 200,
    ball1.y = 240,
    ball2.x = 100,
    ball2.y = 240,
    flag = false,
    vx1 = speed*Math.cos(angle1*Math.PI/180);
    vy1 = speed*Math.sin(angle1*Math.PI/180);
    vx2 = speed*Math.cos(angle2*Math.PI/180);
    vy2 = speed*Math.sin(angle2*Math.PI/180);

(function animate () {
    context.clearRect(0, 0, canvasWidth, canvasHeight);
    window.requestAnimationFrame(animate, canvas);
    if(ball1.x > canvasWidth - ball1.radius || ball1.x  < 0 + ball1.radius) {
        vx1 = -vx1;
    }
    if(ball1.y > canvasHeight - ball1.radius  || ball1.y  < 0 + ball1.radius) {
        vy1 = -vy1;
    }
     if(ball2.x  > canvasWidth - ball2.radius || ball2.x < 0 + ball2.radius) {
        vx2 = -vx2;
    }
    if(ball2.y  > canvasHeight - ball2.radius || ball2.y < 0 + ball2.radius) {
        vy2 = -vy2;
    }

    ball1.x +=vx1; 
    ball1.y +=vy1;  
    ball2.x +=vx2;
    ball2.y +=vy2;

    dist =  calcDistance(ball1.x, ball1.y, ball2.x, ball2.y);       
    if(dist < (ball1.radius + ball2.radius)) {
        flag = true;
    }
    if(flag) {
        document.getElementById("dist").innerHTML = "collision!";
        //Where collision handling of balls should go
        flag = false;
    }
    else {
        document.getElementById("dist").innerHTML = "";
    }
    ball1.draw(context);
    ball2.draw(context);

    function calcDistance(x1, y1, x2, y2) {
        var dx = x1 - x2;
        var dy = y1 - y2;
        var distance = Math.round(Math.sqrt(dx*dx + dy*dy));
        return distance;
    };

  }());
});

I've had a look at this question Ball to Ball Collision - Detection and Handling but I thought there might be an easier way to do it as I can already detect when a collision happens, it was just the handling of that I didn't have but I figured it out by changing the if(flag) statement to this:

if(flag) {
        document.getElementById("dist").innerHTML = "collision!";
        vx1 = -vx1;
        vy1 = -vy1;
        vx2 = -vx2;
        vy2 = -vy2;
        flag = false;
    }
Community
  • 1
  • 1
user3470466
  • 21
  • 1
  • 4

0 Answers0