Math types

kcds.math has Vector2, Vector3, Vector4, Quaternion and Color, on both the server and the client. All of them run inside your resource, so reading or converting a value never contacts the server.

Vectors

Each vector has its components plus:

KindMembers
Changes the vectoradd, sub, mul, div, normalize, lerp, set
Leaves it unchangeddot, distance, length, lengthSquared, clone
TexttoString, toJSON
Staticzero, one

Vector3 also has cross and the static directions up, forward and right.

Methods that change the vector return it, which lets you chain them. Call clone() first if you still need the original. Dividing by zero throws.

const { Vector3 } = kcds.math;

const gate = new Vector3(10, 20, 3);
const aboveGate = gate.clone().add(new Vector3(0, 0, 3));
const height = gate.distance(aboveGate); // 3

World directions: in the game world, Z points up and a character faces +Y. The static helpers Vector3.up() and Vector3.forward() use another common convention, +Y and +Z, so write world directions out yourself, for example new Vector3(0, 0, 1) for up.

Quaternions

The constructor order is (w, x, y, z). Available members are mul, normalize, conjugate, inverse, slerp, dot, rotateVector, toEuler, set, clone, and the static identity, fromEuler and fromAxisAngle.

Units: quaternion methods work in radians. Euler angles given to spawn and teleport calls are in degrees.

const { Quaternion, Vector3 } = kcds.math;

const quarterTurn = Quaternion.fromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
const turned = quarterTurn.rotateVector(new Vector3(0, 1, 0));

To get a point three metres in front of a player, rotate a forward offset by the player's rotation:

const { Vector3 } = kcds.math;

const ahead = player.position.clone().add(player.rotation.rotateVector(new Vector3(0, 3, 0)));

Colours

A Color stores red, green, blue and alpha as numbers from 0 to 1.

  • Create: Color.fromRGB takes bytes from 0 to 255. Color.fromHex takes six or eight hex digits, with or without #, and returns white for anything else.
  • Use: set, lerp, clone, toString and toJSON. toHex() gives the hex form, and toHex(true) includes alpha.
  • Presets: white, black, red, green, blue, yellow, cyan, magenta, transparent.
const { Color } = kcds.math;

const banner = Color.fromRGB(20, 100, 220, 128);
const css = banner.toHex(true);

Reference: Vector3, Quaternion, Color.