Kontra.vector(properties)
- properties {object}
- Properties of the vector.
- properties.x {number}
- Optional. X value. Defaults to 0.
- properties.y {number}
- Optional. Y value. Defaults to 0.
A simple 2d vector object.
Added to the kontra object when kontra.sprite is installed.
kontra.vector(100, 150);
Table of Contents
Extending Functionality
Vectors are very flexible and easy to extend. If you need to modify or add functionality to the vector, you can modify or add to kontra.vector.prototype.
// add magnitude to all vectors
kontra.vector.prototype.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
let vector = kontra.vector(100, 200);
console.log(vector.magnitude()); // => ~223.61
kontra.vector.add(vector, dt)
- vector {kontra.vector}
- Vector to add to the current vector.
- dt {number}
- Optional. Time since last update.
Add two vectors together. Pass dt to adjust how much of the vector gets added.
let vector = kontra.vector(100, 200);
let vector2 = kontra.vector(50, 10);
vector.add(vector2);
console.log(vector); //=> {x: 150, 210}
vector.add(vector2, 0.1);
console.log(vector); //=> {x: 155, 211}
kontra.vector.clamp(xMin, yMin, xMax, yMax)
- xMin {number}
- Optional. Minimum x value. Defaults to -Infinity.
- yMin {number}
- Optional. Minimum y value. Defaults to -Infinity.
- xMax {number}
- Optional. Maximum x value. Defaults to Infinity.
- yMax {number}
- Optional. Maximum y value. Defaults to Infinity.
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.
let vector = kontra.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, 500);
console.log(vector); //=> {x: 0, y: 300}
kontra.vector.x
{number}
X value of the vector.
kontra.vector.y
{number}
Y value of the vector.