UNPKG

kontra

Version:

Kontra HTML5 game development library

102 lines (95 loc) 2.44 kB
/** * A simple 2d vector object. * * ```js * import { Vector } from 'kontra'; * * let vector = Vector(100, 200); * ``` * @class Vector * * @param {Number} [x=0] - X coordinate of the vector. * @param {Number} [y=0] - Y coordinate of the vector. */ class Vector { constructor(x, y) { this._x = x || 0; this._y = y || 0; } /** * Return a new Vector whose value is the addition of the current Vector and the passed in Vector. If `dt` is provided, the result is multiplied by the value. * @memberof Vector * @function add * * @param {kontra.Vector} vector - Vector to add to the current Vector. * @param {Number} [dt=1] - Time since last update. * * @returns {kontra.Vector} A new kontra.Vector instance. */ add(vec, dt) { return vectorFactory( this.x + (vec.x || 0) * (dt || 1), this.y + (vec.y || 0) * (dt || 1) ); } /** * Clamp the Vector between two points, preventing `x` and `y` from going below or above the minimum and maximum values. Perfect for keeping a sprite from going outside the game boundaries. * * ```js * import { Vector } from 'kontra'; * * let vector = Vector(100, 200); * vector.clamp(0, 0, 200, 300); * * vector.x += 200; * console.log(vector.x); //=> 200 * * vector.y -= 300; * console.log(vector.y); //=> 0 * * vector.add({x: -500, y: 500}); * console.log(vector); //=> {x: 0, y: 300} * ``` * @memberof Vector * @function clamp * * @param {Number} xMin - Minimum x value. * @param {Number} yMin - Minimum y value. * @param {Number} xMax - Maximum x value. * @param {Number} yMax - Maximum y value. */ clamp(xMin, yMin, xMax, yMax) { this._c = true; this._a = xMin; this._b = yMin; this._d = xMax; this._e = yMax; } /** * X coordinate of the vector. * @memberof Vector * @property {Number} x */ get x() { return this._x; } /** * Y coordinate of the vector. * @memberof Vector * @property {Number} y */ get y() { return this._y; } set x(value) { this._x = (this._c ? Math.min( Math.max(this._a, value), this._d ) : value); } set y(value) { this._y = (this._c ? Math.min( Math.max(this._b, value), this._e ) : value); } } export default function vectorFactory(x, y) { return new Vector(x, y); } vectorFactory.prototype = Vector.prototype; vectorFactory.class = Vector;