Vector(​[x][, y])

A simple 2d vector object.

let { Vector } = kontra;

let vector = Vector(100, 200);
import { Vector } from 'path/to/kontra.mjs';

let vector = Vector(100, 200);
import { Vector } from 'kontra';

let vector = Vector(100, 200);

Vector Parameters

x Optional

Number. X coordinate of the vector. Defaults to 0.

y Optional

Number. Y coordinate of the vector. Defaults to 0.

Table of Contents

Vector​.add(​vector[, dt])

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.

add Parameters

vector

Vector. Vector to add to the current Vector.

dt Optional

Number. Time since last update. Defaults to 1.

add Return value

A new Vector instance.

Vector​.clamp(​xMin, yMin, xMax, yMax)

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;

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}
import { Vector } from 'path/to/kontra.mjs';

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}
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}

clamp Parameters

xMin

Number. Minimum x value.

yMin

Number. Minimum y value.

xMax

Number. Maximum x value.

yMax

Number. Maximum y value.

Vector​.x

X coordinate of the vector.

Vector​.y

Y coordinate of the vector.