1 /**
  2  * Copyright (C) 2009-2011 Klaus Reimer <k@ailis.de>
  3  * See LICENSE.txt for licensing information.
  4  * 
  5  * @require twodee.js
  6  */
  7 
  8 /**
  9  * Constructs a new bounding box.
 10  * 
 11  * @constructor
 12  * @class
 13  * A bounding box.
 14  */
 15 twodee.BoundingBox = function()
 16 {
 17     twodee.BoundingBox.counter++;
 18 };
 19 
 20 /** 
 21  * Instance counter.
 22  * 
 23  * @type {number}
 24  */
 25 twodee.BoundingBox.counter = 0;
 26 
 27 /**
 28  * The top bound.
 29  * 
 30  * @private
 31  * @type {number}
 32  */
 33 twodee.BoundingBox.prototype.top = Number.POSITIVE_INFINITY;
 34 
 35 /**
 36  * The right bound.
 37  * 
 38  * @private
 39  * @type {number}
 40  */
 41 twodee.BoundingBox.prototype.right = Number.NEGATIVE_INFINITY;
 42 
 43 /**
 44  * The bottom bound.
 45  * 
 46  * @private
 47  * @type {number}
 48  */
 49 twodee.BoundingBox.prototype.bottom = Number.NEGATIVE_INFINITY;
 50 
 51 /**
 52  * The left bound.
 53  * 
 54  * @private
 55  * @type {number}
 56  */
 57 twodee.BoundingBox.prototype.left = Number.POSITIVE_INFINITY;
 58 
 59 /**
 60  * Resets the bounding box to no bounds.
 61  */
 62 twodee.BoundingBox.prototype.reset = function()
 63 {
 64     this.top = Number.POSITIVE_INFINITY;
 65     this.right = Number.NEGATIVE_INFINITY;
 66     this.bottom = Number.NEGATIVE_INFINITY;
 67     this.left = Number.POSITIVE_INFINITY;
 68 };
 69 
 70 /**
 71  * Updates the bounding box with the specified vector
 72  * 
 73  * @param {twodee.Vector} v
 74  *            The vector
 75  */
 76 twodee.BoundingBox.prototype.update = function(v)
 77 {
 78     var x, y;
 79     
 80     x = v.x;
 81     y = v.y;
 82     this.top = Math.min(this.top, y);
 83     this.right = Math.max(this.right, x);
 84     this.bottom = Math.max(this.bottom, y);
 85     this.left = Math.min(this.left, x);
 86 };
 87 
 88 /**
 89  * Checks if this bounding box collides with the specified other bounding
 90  * box.
 91  * 
 92  * @param {twodee.BoundingBox} other
 93  *            The other bounding box
 94  * @return {boolean} True if bounding boxes collide, false if not
 95  */
 96 twodee.BoundingBox.prototype.collidesWith = function(other)
 97 {
 98     return this.top <= other.bottom &&
 99            this.bottom >= other.top &&
100            this.left <= other.right &&
101            this.right >= other.left;
102 };
103 
104 /**
105  * Returns the width of the bounding box.
106  * 
107  * @return {number} The bounding box width
108  */
109 twodee.BoundingBox.prototype.getWidth = function()
110 {
111     return this.right - this.left;
112 };
113 
114 /**
115  * Returns the height of the bounding box.
116  * 
117  * @return {number} The bounding box height
118  */
119 twodee.BoundingBox.prototype.getHeight = function()
120 {
121     return this.bottom - this.top;
122 };
123