Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Vec2

struct Vec2 { x: float, y: float }

A 2D vector with float components x and y. Create one with Vec2::new(x, y) or a struct literal such as Vec2 { x = 1.0, y = 2.0 }.

The components are stored as 32-bit floats, and can read back slightly different from the value that was set (0.1 reads back as 0.10000000149011612).

Implementations

new

fn new(x: float, y: float) -> Vec2

Creates a vector from its x and y components. A struct literal such as Vec2 { x = 3.0, y = 4.0 } does the same.

use std::math::Vec2;

let v = Vec2::new(3.0, 4.0);
let y = v.y; // 4.0

from_angle

fn from_angle(radians: float) -> Vec2

Creates a vector of length 1.0 pointing at an angle of radians, measured from the positive x axis toward the positive y axis. Its components are the angle’s cosine and sine.

use std::math::Vec2;

let right = Vec2::from_angle(0.0);
let x = right.x; // 1.0

length

fn length(self) -> float

normalize

fn normalize(self) -> Vec2

add

fn add(self, other: Vec2) -> Vec2

Returns the sum of the two vectors, adding them component by component.

use std::math::Vec2;

let v = Vec2::new(3.0, 4.0).add(Vec2::new(1.0, 1.0));
let x = v.x; // 4.0

sub

fn sub(self, other: Vec2) -> Vec2

Returns this vector minus other, component by component. b.sub(a) is the vector that points from a to b.

use std::math::Vec2;

let player = Vec2::new(1.0, 1.0);
let enemy = Vec2::new(4.0, 5.0);
let offset = enemy.sub(player);
let x = offset.x; // 3.0

scale

fn scale(self, by: float) -> Vec2

Returns the vector with both components multiplied by by.

use std::math::Vec2;

let half = Vec2::new(3.0, 4.0).scale(0.5);
let x = half.x; // 1.5

dot

fn dot(self, other: Vec2) -> float

Returns the dot product, x * other.x + y * other.y. For two vectors of length 1.0 it’s the cosine of the angle between them, and a result of 0.0 means they’re perpendicular.

use std::math::Vec2;

let a = Vec2::new(3.0, 4.0).dot(Vec2::new(1.0, 0.0)); // 3.0

distance

fn distance(self, other: Vec2) -> float

Returns the straight-line distance between the two points.

use std::math::Vec2;

let d = Vec2::new(0.0, 0.0).distance(Vec2::new(3.0, 4.0)); // 5.0

angle

fn angle(self) -> float

Returns the angle of the vector in radians, measured from the positive x axis toward the positive y axis. The result is between -PI and PI. Vec2::from_angle goes the other way.

use std::math::Vec2;

let a = Vec2::new(1.0, 0.0).angle(); // 0.0

lerp

fn lerp(self, other: Vec2, t: float) -> Vec2

Returns the point that is t of the way from this vector to other, so 0.5 gives the midpoint. t isn’t limited to 0.0 through 1.0: 1.5 goes past other by half the distance again.

use std::math::Vec2;

let start = Vec2::new(0.0, 0.0);
let end = Vec2::new(10.0, 20.0);
let quarter = start.lerp(end, 0.25);
let y = quarter.y; // 5.0