Last active
November 25, 2020 15:57
-
-
Save krutoo/abbd2e8a7096cdd55329f5381e97554d to your computer and use it in GitHub Desktop.
2D immutable vector representation utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { toRadians, toDegrees } from './math.js'; | |
export const Vec2 = { | |
of (x, y) { | |
return { x, y }; | |
}, | |
length (v) { | |
return Math.sqrt(v.x ** 2 + v.y ** 2); | |
}, | |
angle (v) { | |
return toDegrees(Math.atan2(v.y, v.x)); | |
}, | |
equals (v1, v2) { | |
return v1.x === v2.x && v1.y === v2.y; | |
}, | |
distance (v1, v2) { | |
return Vec2.length(Vec2.subtract(v1, v2)) | |
}, | |
add (v1, v2) { | |
return Vec2.of(v1.x + v2.x, v1.y + v2.y); | |
}, | |
subtract (v1, v2) { | |
return Vec2.of(v1.x - v2.x, v1.y - v2.y); | |
}, | |
cross (v1, v2) { | |
return Vec2.of(v1.x * v2.x, v1.y * v2.y); | |
}, | |
multiplyScalar (v, scalar = 1) { | |
return Vec2.of(v.x * scalar, v.y * scalar); | |
}, | |
normalize (v) { | |
return Vec2.multiplyScalar(v, 1 / Vec2.length(v)); | |
}, | |
rotate (v, radians = 0, c = Vec2.of(0, 0)) { | |
return Vec2.of( | |
c.x + (v.x - c.x) * Math.cos(radians) - (v.y - c.y) * Math.sin(radians), | |
c.y + (v.x - c.x) * Math.sin(radians) + (v.y - c.y) * Math.cos(radians) | |
); | |
}, | |
reverse (v) { | |
return Vec2.rotate(v, toRadians(180)); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment