boids/vector.mjs

78 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-05-04 15:17:55 +00:00
class Vector
{
constructor(x = 0, y = 0)
{
this.x = x;
this.y = y;
}
add(vector)
{
return new Vector(this.x + vector.x, this.y + vector.y);
}
addMut(vector)
{
this.x += vector.x;
this.y += vector.y;
return this;
}
sub(vector)
{
return new Vector(this.x - vector.x, this.y - vector.y);
}
subMut(vector)
{
this.x -= vector.x;
this.y -= vector.y;
return this;
}
mul(scalar)
{
return new Vector(this.x * scalar, this.y * scalar);
}
mulMut(scalar)
{
this.x *= scalar;
this.y *= scalar;
return this;
}
div(scalar)
{
return this.mul(1 / scalar);
}
divMut(scalar)
{
return this.mulMut(1 / scalar);
}
rotate(angle)
{
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return new Vector(
cos * this.x - sin * this.y,
cos * this.y + sin * this.x,
);
}
angle()
{
return Math.PI / 2 - Math.atan2(this.x, this.y);
}
normSquared()
{
return this.x * this.x + this.y * this.y;
}
}
export default Vector;