-
Notifications
You must be signed in to change notification settings - Fork 24
Vector Math
Rich Lane edited this page May 4, 2023
·
4 revisions
Two-dimensional floating point vectors (Vec2) are ubiquitous in Oort and are used to represent positions, velocities, accelerations, etc.
Angles in the Cartesian coordinate system
Quick reference:
-
vec2(x: f64, y: f64) → Vec2
: Create a vector. -
v.x, v.y → f64
: Get a component of a vector. -
v1 +- v2 → Vec2
: Basic arithmetic between vectors. -
v */ f64 → Vec2
: Basic arithmetic between vectors and scalars. -
-v → Vec2
: Negate a vector. -
v.length() → f64
: Length. -
v.normalize() → Vec2
: Normalize to a unit vector. -
v.rotate(angle: f64) → Vec2
: Rotate counter-clockwise. -
v.angle() → f64
: Angle of a vector. -
v1.dot(v2: Vec2) → f64
: Dot product. -
v1.cross(v2: Vec2) → f64
: Cross product. -
v1.distance(v2: Vec2) → f64
: Distance between two points.
Vec2
is a two-dimensional floating point vector, so it has x
and y
fields with type f64
. This is convenient for storing positions, velocities, accelerations, etc, because operations can work on both components at the same time. For example: vec2(a, b) + vec2(c, d) == vec2(a + c, b + d)
. Here's a list of how the basic operations expand:
vec2(a, b) + vec2(c, d) == vec2(a + c, b + d)
vec2(a, b) - vec2(c, d) == vec2(a - c, b - d)
vec2(a, b) * c == vec2(a * c, b * c)
-vec2(a, b) == vec2(-a, -b)
You can get the length of a vector with the length()
method, and the distance between two vectors with v1.distance(v2)
.
All angles are in radians, and are relative to the positive X axis. For example:
vec2(1.0, 0.0).angle() == 0.0 // Pointing east
vec2(0.0, 1.0).angle() == PI / 2.0 // Pointing north
vec2(1.0, 0.0).rotate(PI / 2.0) == PI / 2.0 // Pointing north
Examples:
// Accelerate towards position "p"
accelerate(p - position());
// Get the angle between your ship and another position "p"
let angle = (p - position()).angle();
// Turn to point at "angle"
turn(angle_diff(heading(), angle));