Rectangle

The Rectangle class represents an axis-aligned bounding rectangle (AABR) defined by position, width, and height.
The position represents the bottom-left corner of the rectangle.
It provides methods and properties for manipulating and querying the rectangle’s geometry.

Properties

PropertyTypeDescription
xnumberX coordinate of the bottom-left corner.
ynumberY coordinate of the bottom-left corner.
x1numberX coordinate of the right edge (x + width).
y1numberY coordinate of the top edge (y + height).
widthnumberRectangle’s width.
heightnumberRectangle’s height.
positionVector2Vector representing the position (x, y).
centerVector2Vector representing the center of the rectangle.

Instance methods

MethodReturnsDescription
set(x, y, width, height)voidSets the position and dimensions of the rectangle.
equals(rectangle)booleanCompares if two rectangles are equal.
copy(rect)voidCopies the properties from another rectangle.
intersects(rect)booleanChecks if this rectangle overlaps with another rectangle.
contains(rect or vector)booleanChecks if the rectangle fully contains another rectangle or a point (Vector2).
toString()stringReturns a string representation of the rectangle.

Basic example

const rect = new Rectangle(0, 0, 100, 100);

console.log(rect.width); // 100
console.log(rect.height); // 100
console.log(rect.x); // 0
console.log(rect.y); // 0
console.log(rect.x1); // 100
console.log(rect.y1); // 100

console.log(rect.center); // Vector2 { x: 50, y: 50 }

Example: intersection and containment

const rect1 = new Rectangle(0, 0, 100, 100);
const rect2 = new Rectangle(50, 50, 100, 100);

console.log(rect1.intersects(rect2)); // true

const point = new Vector2(50, 50);
console.log(rect1.contains(point)); // true

const rect3 = new Rectangle(100, 100, 100, 100);
console.log(rect1.contains(rect3)); // false

Notes

  • The x and y position always represents the bottom-left corner.
  • The intersects and contains methods are essential for collision detection in physics and rendering systems.
  • The center property is dynamically calculated on each access and does not create new instances thanks to using an internal reference.