Skip to content

Instantly share code, notes, and snippets.

@un4ckn0wl3z
Created December 11, 2025 09:40
Show Gist options
  • Select an option

  • Save un4ckn0wl3z/fbf494d6258fa9515a816b50001f402d to your computer and use it in GitHub Desktop.

Select an option

Save un4ckn0wl3z/fbf494d6258fa9515a816b50001f402d to your computer and use it in GitHub Desktop.
class Vec3 {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
add(v) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
}
static add(a, b) {
return new Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
}
sub(v) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
}
static sub(a, b) {
return new Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
}
scale(n) {
this.x *= n;
this.y *= n;
this.z *= n;
}
dot(v){
return (this.x * v.x + this.y * v.y + this.z * v.z);
}
mag() {
return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z);
}
cross(v) {
return new Vec3(
this.y * v.z - this.z * v.y,
this.z * v.x - this.x * v.z,
this.x * v.y - this.y * v.x
);
}
normalize() {
let len = this.mag();
this.x /= len;
this.y /= len;
this.z /= len;
}
}
// ===================== Vec2 =====================
class Vec2 {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(v) {
this.x += v.x;
this.y += v.y;
}
static add(a, b){
return new Vec2(a.x + b.x, a.y + b.y);
}
sub(v) {
this.x -= v.x;
this.y -= v.y;
}
static sub(a, b){
return new Vec2(a.x - b.x, a.y - b.y);
}
scale(n){
this.x *= n;
this.y *= n;
}
dot(v) {
return (this.x * v.x + this.y * v.y);
}
// perpendicular normal (right-hand)
perpendicular(){
return new Vec2(this.y, -this.x);
}
mag() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
normalize() {
let len = this.mag();
this.x /= len;
this.y /= len;
}
rotate(angle) {
return new Vec2(
this.x * Math.cos(angle) - this.y * Math.sin(angle),
this.x * Math.sin(angle) + this.y * Math.cos(angle)
);
}
draw(color) {
stroke("white");
fill(color);
line(0, 0, this.x, this.y);
circle(this.x, this.y, 10);
}
}
// positions
let position1 = new Vec2(100, 0);
let position2 = new Vec2(200, -100);
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background("black");
translate(windowWidth/2, windowHeight/2);
// Draw points
position1.draw("red");
position2.draw("blue");
// Draw segment
stroke("white");
line(position1.x, position1.y, position2.x, position2.y);
// Compute direction vector
let dir = Vec2.sub(position2, position1);
// Normal vector
let normal = dir.perpendicular();
normal.normalize();
normal.scale(70); // make it visible
// midpoint
let mid = new Vec2(
(position1.x + position2.x) / 2,
(position1.y + position2.y) / 2
);
// Draw normal from midpoint
push();
translate(mid.x, mid.y);
normal.draw("green");
pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment