UNPKG

aabb-2d

Version:

2d axis aligned bounding boxes

94 lines (69 loc) 1.81 kB
module.exports = AABB var vec2 = require('gl-matrix').vec2 function AABB(pos, vec) { if(!(this instanceof AABB)) { return new AABB(pos, vec) } this.base = pos this.vec = vec this.mag = vec2.length(this.vec) this.max = vec2.create() vec2.add(this.max, this.base, this.vec) } var cons = AABB , proto = cons.prototype proto.perimeter = function() { return 2 * (this.vec[0] + this.vec[1]) } proto.area = function() { return this.vec[0] * this.vec[0] + this.vec[1] * this.vec[1] } proto.intperimeter = function() { return (this.vec[0] + this.vec[1]) << 1 } proto.width = function() { return this.vec[0] } proto.height = function() { return this.vec[1] } proto.x0 = function() { return this.base[0] } proto.y0 = function() { return this.base[1] } proto.x1 = function() { return this.max[0] } proto.y1 = function() { return this.max[1] } proto.translate = function(by) { vec2.add(this.max, this.max, by) vec2.add(this.base, this.base, by) return this } proto.expand = function(aabb) { var max = vec2.create() , min = vec2.create() vec2.max(max, aabb.max, this.max) vec2.min(min, aabb.base, this.base) vec2.sub(max, max, min) return new AABB(min, max) } proto.intersects = function(aabb) { if(aabb.base[0] > this.max[0]) return false if(aabb.base[1] > this.max[1]) return false if(aabb.max[0] < this.base[0]) return false if(aabb.max[1] < this.base[1]) return false return true } proto.union = function(aabb) { if(!this.intersects(aabb)) return null var base_x = Math.max(aabb.base[0], this.base[0]) , base_y = Math.max(aabb.base[1], this.base[1]) , max_x = Math.min(aabb.max[0], this.max[0]) , max_y = Math.min(aabb.max[1], this.max[1]) return new AABB([base_x, base_y], [max_x - base_x, max_y - base_y]) }