Skip to content

Latest commit

 

History

History

README.md

Math utilities

CDN: https://unpkg.com/@litecanvas/utils/dist/math.js

diff

Calculates the positive distance/difference of two given numbers.

Syntax: diff(a: number, b: number): number

import litecanvas from "litecanvas"
import { diff } from "@litecanvas/utils"

litecanvas({
  loop: { init },
})

function init() {
  console.log(diff(10, 5)) // outputs 5
  console.log(diff(-10, 5)) // outputs 15
}

fract

Returns the fractional part of a number.

Syntax: fract(value: number): number

import litecanvas from "litecanvas"
import { fract } from "@litecanvas/utils"

litecanvas({
  loop: { init },
})

function init() {
  console.log(fract(5.9)) // outputs 0.9
}

advance

Move a vector (position) using another vectors: velocity (required) and acceleration (optional).

Note: This function changes the position and velocity vectors.

Syntax: advance(position: Vector, velocity: Vector, acceleration?: Vector, delta?: number): void

import litecanvas from "litecanvas"
import { vec, advance } from "@litecanvas/utils"

litecanvas()

function init() {
  pos = vec(0, H / 2)
  vel = vec(0, 0)
  acc = vec(100, 0)
}

function update(dt) {
  advance(pos, vel, acc, dt)
  if (pos.x > W) {
    pos.x = 0
  }
}

function draw() {
  cls(0)
  circ(pos.x, pos.y, 48, 4)
}

See in playground

mod

Math modulus (always returns a positive number).

Syntax: mod(dividend: number, divisor: number): number

import { mod } from "@litecanvas/utils"

mod(17, 5) // => 2
mod(-17, 5) // => 3

mean

Computes the mean of the values in a array.

import { mean } from "@litecanvas/utils"

Syntax: `mean(values: number[]): number`

mean([10, 5, 3]) // => 6 or (10 + 5 + 3) / 3

sum

Computes the sum of the values in a array.

Syntax: sum(values: number[]): number

import { sum } from "@litecanvas/utils"

sum([10, 5, 3]) // => 18 or (10 + 5 + 3)

lerpAngle

Calculates the linear interpolation of two angles (in degrees).

Syntax: lerpAngle(start: number, end: number, amount: number): number

import { lerpAngle } from "@litecanvas/utils"

lerpAngle(0, 90, 0.5) // => 45
lerpAngle(0, 270, 0.5) // => -45