Vector2D
A 2D vector class for positions, velocities, forces, and directions.
Every moving object in every DN game has a Vector2D pos and usually a Vector2D vel.
Include
<script src="/js/dn/mathUtils.js"></script>
Vector2D is defined in mathUtils.js alongside standalone helpers like clamp, lerp,
xFromDistAngle, and yFromDistAngle.
Constructor
const v = new Vector2D(x, y); // defaults: x=0, y=0
const zero = new Vector2D(); // (0, 0)
Properties
| Property | Type | Description |
|---|---|---|
x | number | Horizontal component |
y | number | Vertical component |
Methods
All methods that return a new vector do not modify this — they return a new Vector2D.
Methods that modify in-place (like normalize(), setMag()) are noted.
v.add(other) // returns new Vector2D(v.x + other.x, v.y + other.y)
v.subtract(other) // returns new Vector2D(v.x - other.x, v.y - other.y)
v.scale(s) // returns new Vector2D(v.x * s, v.y * s)
v.multiply(other) // component-wise multiply, returns new Vector2D
v.divide(other) // component-wise divide, returns new Vector2D
v.clone() // returns a copy of this vector
v.getMag() // returns √(x² + y²)
v.normalize() // modifies in-place — sets length to 1
v.getNormalized() // returns a normalized copy, does not modify this
v.setMag(m) // modifies in-place — normalizes then scales to m
v.dot(other) // returns dot product (scalar)
v.distanceTo(other) // returns distance between two points
v.toString() // "Vector2D(x.xxx, y.xxx)"
Common Patterns
Moving an object at constant speed
const pos = new Vector2D(100, 100);
const vel = new Vector2D(200, -150); // pixels per second
function update(dt) {
pos.x += vel.x * dt;
pos.y += vel.y * dt;
}
Pointing one object toward another
const diff = target.pos.subtract(entity.pos); // direction vector
diff.setMag(entity.speed); // scale to speed
entity.vel = diff; // point toward target
Gravity / attraction force (used in LoopShoots)
const diff = new Vector2D(
attractor.pos.x - ball.pos.x,
attractor.pos.y - ball.pos.y
);
diff.setMag(gravityStrength); // normalize + set pull force
ball.vel.x += diff.x;
ball.vel.y += diff.y;
ball.vel.setMag(ball.speed); // clamp to max speed
Standalone Math Helpers (same file)
// Polar → cartesian (used in orbit/circle animations)
xFromDistAngle(distance, angle, isDegrees = false)
yFromDistAngle(distance, angle, isDegrees = false)
// Clamp a value between min and max
clamp(value, min, max)
// Linear interpolation
lerp(a, b, t) // t = 0..1
Source
public/js/dn/mathUtils.js