DieterHolvoet
1/17/2016 - 4:45 PM

Collision detection between an object and an unlimited amount of other objects. Objects must have the following attributes: x, y, width/w/si

Collision detection between an object and an unlimited amount of other objects. Objects must have the following attributes: x, y, width/w/size, height/h/size;

// Source: https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
Object.prototype.collidedWith = function() {
    if(arguments.length > 0) {
        if(this.hasOwnProperty("width")) this.w = this.width;
        if(this.hasOwnProperty("height")) this.h = this.height;
        if(this.hasOwnProperty("size")) this.h = this.w = this.size;
        
        for(var i = 0; i < arguments.length; i++) {
            var o = arguments[i];
            if(o.hasOwnProperty("width")) o.w = o.width;
            if(o.hasOwnProperty("height")) o.h = o.height;
            if(o.hasOwnProperty("size")) o.h = o.w = o.size;

            var a = this.x < o.x + o.w,
                b = this.x + this.w > o.x,
                c = this.y < o.y + o.h,
                d = this.h + this.y > o.y;

            if(a && b && c && d) return true;
        }

        return false;
        
    } else {
        console.error("Object.prototype.collidedWith: No arguments");
    }
};