Added shape drawing and more vector helper functions

This commit is contained in:
Mitchell McCaffrey
2020-04-27 21:39:21 +10:00
parent e08dc60f5f
commit 81f84d8a19
6 changed files with 278 additions and 62 deletions
+54 -2
View File
@@ -1,3 +1,5 @@
import { toRadians } from "./shared";
export function lengthSquared(p) {
return p.x * p.x + p.y * p.y;
}
@@ -8,7 +10,7 @@ export function length(p) {
export function normalize(p) {
const l = length(p);
return { x: p.x / l, y: p.y / l };
return divide(p, l);
}
export function dot(a, b) {
@@ -16,5 +18,55 @@ export function dot(a, b) {
}
export function subtract(a, b) {
return { x: a.x - b.x, y: a.y - b.y };
if (typeof b === "number") {
return { x: a.x - b, y: a.y - b };
} else {
return { x: a.x - b.x, y: a.y - b.y };
}
}
export function add(a, b) {
if (typeof b === "number") {
return { x: a.x + b, y: a.y + b };
} else {
return { x: a.x + b.x, y: a.y + b.y };
}
}
export function multiply(a, b) {
if (typeof b === "number") {
return { x: a.x * b, y: a.y * b };
} else {
return { x: a.x * b.x, y: a.y * b.y };
}
}
export function divide(a, b) {
if (typeof b === "number") {
return { x: a.x / b, y: a.y / b };
} else {
return { x: a.x / b.x, y: a.y / b.y };
}
}
export function rotate(point, origin, angle) {
const cos = Math.cos(toRadians(angle));
const sin = Math.sin(toRadians(angle));
const dif = subtract(point, origin);
return {
x: origin.x + cos * dif.x - sin * dif.y,
y: origin.y + sin * dif.x + cos * dif.y,
};
}
export function rotateDirection(direction, angle) {
return rotate(direction, { x: 0, y: 0 }, angle);
}
export function min(a) {
return a.x < a.y ? a.x : a.y;
}
export function max(a) {
return a.x > a.y ? a.x : a.y;
}