Collisions and Animation

by sirfizx

HTML

<div id="position"></div>
<canvas id="myCanvas" width="600" height="400"></canvas>

JavaScript

var timer = window.setInterval(callAnimation, 50);

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };
})();

var step = 2;

var yellowRectangle = {
    x: 200,
    y: 200,
    width: 10,
    height: 10,
    borderWidth: 1,
    borderColor: 'black',
    fillColor: 'yellow'
};

var greenRectangle = 
 {
    x: 200,
    y: 200,
    width: 10,
    height: 10,
    borderWidth: 1,
    borderColor: 'black',
    fillColor: 'green'
};

var rectangles = new Array();
rectangles[0] = yellowRectangle;
rectangles[1] = greenRectangle;

function drawRectangle(r, c) {
    c.beginPath();
    c.rect(r.x, r.y, r.width, r.height);
    c.fillStyle = r.fillColor;
    c.fill();
    c.lineWidth = r.borderWidth;
    c.strokeStyle = r.borderColor;
    c.stroke();
}

function callAnimation() {
    requestAnimFrame(function () {
        animate(rectangles, canvas, context);
    });
}

function animate(r, can, con)
{
    if (r[0].x < 100 || r[0].x > 300) step *= -1;
    r[0].x += step;
    r[1].y += step;     
    con.clearRect(0, 0, can.width, can.height);
    
    var rc0 = r[0].fillColor;
    var rc1 = r[1].fillColor;
    
    if (collision(r[0], r[1]))
    {
        r[0].fillColor = 'red';
        r[1].fillColor = 'red';
    }
    
    drawRectangle(r[0], con);
    drawRectangle(r[1], con);
    
    r[0].fillColor = rc0;
    r[1].fillColor = rc1;
}

function collision(r1, r2)
{   
    if (pointIsInRectangle(r1.x, r1.y, r2)) return true;
    if (pointIsInRectangle(r1.x + r1.width, r1.y, r2)) return true; 
    if (pointIsInRectangle(r1.x + r1.width, r1.y + r1.height, r2)) return true; 
    if (pointIsInRectangle(r1.x, r1.y + r1.height, r2)) return...