In raw Markdown, write a short guide accompanied by an exhaustive set of usage examples…
- User
In raw Markdown, write a short guide accompanied by an exhaustive set of usage examples for this class:
rustuse std::ops::{Add, Sub, Mul, Div}; #[derive(Debug, PartialEq, Clone, Copy)] struct Vector2 { x: f32, y: f32, } impl Vector2 { pub fn new(x: f32, y: f32) -> Self { Vector2 { x, y } } pub fn zero() -> Self { Vector2::new(0.0, 0.0) } pub fn one() -> Self { Vector2::new(1.0, 1.0) } pub fn up() -> Self { Vector2::new(0.0, 1.0) } pub fn down() -> Self { Vector2::new(0.0, -1.0) } pub fn left() -> Self { Vector2::new(-1.0, 0.0) } pub fn right() -> Self { Vector2::new(1.0, 0.0) } pub fn magnitude(self) -> f32 { (self.x.powi(2) + self.y.powi(2)).sqrt() } pub fn sqr\_magnitude(self) -> f32 { self.x.powi(2) + self.y.powi(2) } pub fn distance(self, other: Vector2) -> f32 { (self - other).magnitude() } pub fn sqr\_distance(self, other: Vector2) -> f32 { (self - other).sqr\_magnitude() } pub fn normalized(self) -> Self { let mag = self.magnitude(); if mag != 0.0 { self / mag } else { self } } pub fn dot(self, other: Vector2) -> f32 { self.x \* other.x + self.y \* other.y } pub fn angle(self, other: Vector2) -> f32 { let dot = self.dot(other); let mag\_product = self.magnitude() \* other.magnitude(); if mag\_product != 0.0 { dot.acos() \* 180.0 / std::f32::consts::PI } else { 0.0 } } pub fn cross(self, other: Vector2) -> f32 { self.x \* other.y - self.y \* other.x } pub fn lerp(self, other: Vector2, t: f32) -> Self { self \* (1.0 - t) + other \* t } pub fn reflect(self, normal: Vector2) -> Self { self - normal \* 2.0 \* self.dot(normal) } pub fn angle\_between(self, other: Vector2) -> f32 { let cross = self.cross(other); let dot = self.dot(other); cross.atan2(dot) \* 180.0 / std::f32::consts::PI } } - Assistant
Guide to the Vector2 Struct in Rust
The
Vector2struct represents a two-dimensional vector withxand components. It is designed to be used in applications that require vector calculations, such as games, simulations, and graphics. - User
Continue that from "`angle" without repeating the first part
- Assistant
angle(other: Vector2) -> f32
Returns the angle in degrees between the vector and another vector
other.Example:
rustlet v1 = Vector2::new(1.0, 1.0); let v2 = Vector2::new(-1.0, 1.0); let angle = v1.angle(v2); assert_eq!(angle, 90.0);cross(other: Vector2) -> f32
Returns the cross product of the vector and another vector
other.Example:
rustlet v1 = Vector2::new(2.0, 3.0); let v2 = Vector2::new(4.0, 5.0); let cross = v1.cross(v2); assert_eq!(cross, -2.0);lerp(other: Vector2, t: f32) -> Vector2
Linearly interpolates between the vector and another vector
otherby a valuetbetween 0 and 1.Example: