Skip to content

Instantly share code, notes, and snippets.

@foopis23
Created February 22, 2022 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foopis23/4c876e776dcd01b42007e6e83ac14eae to your computer and use it in GitHub Desktop.
Save foopis23/4c876e776dcd01b42007e6e83ac14eae to your computer and use it in GitHub Desktop.
Simple Vector2 Math
export interface Vector2 {
x: number
y: number
}
const distance = (a: Vector2, b: Vector2): number =>
Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2)
const subtract = (b: Vector2, a: Vector2): Vector2 => {
return { x: b.x - a.x, y: b.y - a.y }
}
const length = (v: Vector2): number => Math.sqrt((v.x ** 2 + v.y ** 2))
const normalize = (v: Vector2): Vector2 => {
const mag = length(v)
return { x: v.x / mag, y: v.y / mag }
}
const dot = (a: Vector2, b: Vector2): number => a.x * b.x + a.y * b.y
const angle = (a: Vector2, b: Vector2): number => dot(a, b) / (length(a) * length(b))
export const mathv2 = {
distance,
subtract,
length,
normalize,
dot,
angle
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment