pub struct Vec2<T> {
pub x: T,
pub y: T,
}Expand description
Represents a 2D vector with generic numeric components.
Vec2 is a generic structure that represents a 2-dimensional vector with components x and y.
It provides a variety of methods for vector operations, including vector arithmetic,
normalization, dot product, distance calculation, and linear interpolation.
§Type Parameters
T: The numeric type of the vector components. This type must implement certain traits such asZero,One,NumAssign,Copy, and others depending on the method.
Fields§
§x: T§y: TImplementations§
Source§impl<T> Vec2<T>
impl<T> Vec2<T>
Sourcepub fn set(v: T) -> Self
pub fn set(v: T) -> Self
Creates a vector with both components set to the given value v.
§Parameters
v: The value to be assigned to both the x and y components of the vector.
§Returns
A Vec2 instance where both components are initialized to v.
§Example
let vec = Vec2::set(5.0);
assert_eq!(vec.x, 5.0);
assert_eq!(vec.y, 5.0);Sourcepub fn from_vec3(v: &Vec3<T>) -> Self
pub fn from_vec3(v: &Vec3<T>) -> Self
Creates a Vec2 from a Vec3 by using the x and y components of the Vec3.
This is useful when you want to convert a 3-dimensional vector to a 2-dimensional vector,
discarding the z component.
§Parameters
v: A reference to aVec3instance from which thexandycomponents will be used.
§Returns
A Vec2 instance with the x and y components taken from the Vec3 instance.
§Example
let vec3 = Vec3::new(1.0, 2.0, 3.0);
let vec2 = Vec2::from_vec3(&vec3);
assert_eq!(vec2.x, 1.0);
assert_eq!(vec2.y, 2.0);Sourcepub fn from_vec4(v: &Vec4<T>) -> Self
pub fn from_vec4(v: &Vec4<T>) -> Self
Creates a Vec2 from a Vec4 by using the x and y components of the Vec4.
This is useful when you want to convert a 4-dimensional vector to a 2-dimensional vector,
discarding the z and w components.
§Parameters
v: A reference to aVec4instance from which thexandycomponents will be used.
§Returns
A Vec2 instance with the x and y components taken from the Vec4 instance.
§Example
let vec4 = Vec4::new(1.0, 2.0, 3.0, 4.0);
let vec2 = Vec2::from_vec4(&vec4);
assert_eq!(vec2.x, 1.0);
assert_eq!(vec2.y, 2.0);Sourcepub fn dot(&self, other: &Self) -> T
pub fn dot(&self, other: &Self) -> T
Computes the dot product of the vector with another vector.
The dot product is calculated as the sum of the products of the corresponding components of the two vectors. It is a measure of how much one vector extends in the direction of another. The result is a scalar value.
§Arguments
other: The other vector with which to compute the dot product.
§Returns
The dot product of the two vectors as a value of type T.
§Constraints
Tmust implement theMulandAddtraits to support multiplication and addition operations.
§Example
let vec1 = Vec2::new(1.0, 2.0);
let vec2 = Vec2::new(3.0, 4.0);
assert_eq!(vec1.dot(&vec2), 11.0);Sourcepub fn length_squared(&self) -> T
pub fn length_squared(&self) -> T
Computes the squared length (or magnitude) of the vector.
The squared length is calculated as the sum of the squares of the components of the vector. This is often used in computations where you need the length of the vector but want to avoid the overhead of computing the square root.
§Returns
The squared length of the vector as a value of type T. This is the result of the expression
x * x + y * y.
§Constraints
Tmust implement theMulandAddtraits to support multiplication and addition operations.
§Example
let vec = Vec2::new(3.0, 4.0);
assert_eq!(vec.length_squared(), 25.0);Sourcepub fn distance_squared(&self, other: &Self) -> T
pub fn distance_squared(&self, other: &Self) -> T
Computes the squared distance between this vector and another vector.
This method calculates the squared distance between the two vectors without computing the square root, which can be more efficient, especially when comparing distances or performing multiple distance calculations.
§Arguments
other: The other vector to which the squared distance is calculated.
§Returns
The squared distance between the two vectors as a value of type T.
§Constraints
Tmust implement theSubandMultraits to support subtraction and multiplication operations.
§Example
let vec1 = Vec2::new(1.0, 2.0);
let vec2 = Vec2::new(4.0, 6.0);
assert_eq!(vec1.distance_squared(&vec2), 25.0);Sourcepub fn transform_mat2(&self, transform: &Mat2<T>) -> Self
pub fn transform_mat2(&self, transform: &Mat2<T>) -> Self
Transforms a 2D vector using a 2x2 matrix.
This method applies a 2D affine transformation to a Vec2<T> using a Mat2<T> matrix.
The matrix multiplication is performed as follows:
[ x' ] = [ m00 m01 ] [ x ] = [ m00 * x + m01 * y ]
[ y' ] [ m10 m11 ] [ y ] [ m10 * x + m11 * y ]where Vec2<T> is represented as [x, y] and Mat2<T> is represented as:
[ m00 m01 ]
[ m10 m11 ]Parameters:
transform: A reference to aMat2<T>matrix representing the 2D transformation to be applied.
Returns:
- A new
Vec2<T>that is the result of transforming the original vector by the matrix.
Example:
let vec = Vec2::new(1.0, 2.0);
let mat = Mat2::new(&Vec2::new(1.0, 0.0), &Vec2::new(0.0, 1.0));
let transformed_vec = vec.transform_mat2(&mat);
assert_eq!(transformed_vec, Vec2::new(1.0, 2.0));This example shows a simple case where the matrix is the identity matrix, and hence the vector remains unchanged.
Sourcepub fn transform_mat3(&self, transform: &Mat3<T>) -> Self
pub fn transform_mat3(&self, transform: &Mat3<T>) -> Self
Transforms a 2D vector using a 3x3 matrix.
This method applies a 2D affine transformation to a Vec2<T> using a Mat3<T> matrix.
The matrix multiplication is performed as follows:
[ x' ] = [ m00 m01 m02 ] [ x ] = [ m00 * x + m01 * y + m02 ]
[ y' ] [ m10 m11 m12 ] [ y ] [ m10 * x + m11 * y + m12 ]
[ w' ] [ 0 0 1 ] [ 1 ] [ 1 ] // Homogeneous coordinatewhere Vec2<T> is represented as [x, y] and Mat3<T> is represented as:
[ m00 m01 m02 ]
[ m10 m11 m12 ]
[ 0 0 1 ]Parameters:
transform: A reference to aMat3<T>matrix representing the 2D affine transformation to be applied.
Returns:
- A new
Vec2<T>that is the result of transforming the original vector by the matrix.
Example:
let vec = Vec2::new(1.0, 2.0);
let mat = Mat3::new(
Vec3::new(1.0, 0.0, 3.0), // Translation x
Vec3::new(0.0, 1.0, 4.0), // Translation y
Vec3::new(0.0, 0.0, 1.0) // Homogeneous coordinate
);
let transformed_vec = vec.transform_mat3(&mat);
assert_eq!(transformed_vec, Vec2::new(4.0, 6.0));In this example, the Mat3 matrix represents a translation, moving the vector (1.0, 2.0)
to (4.0, 6.0).
Source§impl<T> Vec2<T>
impl<T> Vec2<T>
Sourcepub fn min(&self, other: &Self) -> Self
pub fn min(&self, other: &Self) -> Self
Returns a new Vec2 containing the component-wise minimum of self and other.
For each component x and y, the method compares the corresponding components of
self and other and returns the smaller of the two.
§Parameters
other: A reference to anotherVec2instance to compare withself.
§Returns
A new Vec2 where each component is the minimum value between self and other.
§Examples
let vec1 = Vec2::new(3, 7);
let vec2 = Vec2::new(4, 5);
let min_vec = vec1.min(&vec2);
assert_eq!(min_vec, Vec2::new(3, 5));Sourcepub fn max(&self, other: &Self) -> Self
pub fn max(&self, other: &Self) -> Self
Returns a new Vec2 containing the component-wise maximum of self and other.
For each component x and y, the method compares the corresponding components of
self and other and returns the larger of the two.
§Parameters
other: A reference to anotherVec2instance to compare withself.
§Returns
A new Vec2 where each component is the maximum value between self and other.
§Examples
let vec1 = Vec2::new(3, 7);
let vec2 = Vec2::new(4, 5);
let max_vec = vec1.max(&vec2);
assert_eq!(max_vec, Vec2::new(4, 7));Sourcepub fn clamp(&self, min: &Self, max: &Self) -> Self
pub fn clamp(&self, min: &Self, max: &Self) -> Self
Clamps the components of self to lie within the inclusive range defined by min and max.
For each component x and y, the method compares the corresponding component of self
to the provided min and max values and ensures it lies within this range. If a component
of self is less than the corresponding component of min, it is set to the min value.
If it is greater than the corresponding component of max, it is set to the max value.
§Parameters
min: A reference to aVec2representing the minimum allowed values for each component.max: A reference to aVec2representing the maximum allowed values for each component.
§Returns
A new Vec2 where each component is clamped to the range [min, max].
§Panics
This method will panic if any component of min is greater than the corresponding component
of max, as it is not possible to clamp a value within an invalid range.
§Examples
let vec = Vec2::new(5, 10);
let min_vec = Vec2::new(3, 7);
let max_vec = Vec2::new(6, 8);
let clamped_vec = vec.clamp(&min_vec, &max_vec);
assert_eq!(clamped_vec, Vec2::new(5, 8));Source§impl<T> Vec2<T>
impl<T> Vec2<T>
Sourcepub fn length(&self) -> T
pub fn length(&self) -> T
Returns the length (magnitude) of the vector.
The length of the vector is calculated as the Euclidean norm, which is the square root of the sum of the squares of its components.
§Returns
The length (magnitude) of the vector as a value of type T.
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let vec = Vec2::new(3.0, 4.0);
assert_eq!(vec.length(), 5.0);Sourcepub fn normalize(&self) -> Option<Self>
pub fn normalize(&self) -> Option<Self>
Returns a normalized (unit length) version of the vector.
The normalized vector is a unit vector that points in the same direction as the original vector.
Normalization is achieved by dividing each component of the vector by its length.
If the vector has zero length (is a zero vector), None is returned to indicate that normalization is not possible.
§Returns
Some(Self): A new vector with unit length pointing in the same direction as the original vector, if normalization is possible.None: If the vector has zero length, indicating that it cannot be normalized.
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let vec = Vec2::new(3.0, 4.0);
let normalized = vec.normalize().unwrap();
assert_eq!(normalized.length(), 1.0);Sourcepub fn distance(&self, other: &Self) -> T
pub fn distance(&self, other: &Self) -> T
Computes the distance between this vector and another vector.
The distance is calculated as the Euclidean distance between the two vectors, which is the length of the vector representing the difference between them.
§Arguments
other: The other vector to which the distance is calculated.
§Returns
The distance between the two vectors as a value of type T.
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let vec1 = Vec2::new(1.0, 2.0);
let vec2 = Vec2::new(4.0, 6.0);
assert_eq!(vec1.distance(&vec2), 5.0);Sourcepub fn direction(&self, other: &Self) -> Option<Self>
pub fn direction(&self, other: &Self) -> Option<Self>
Computes the direction from this vector to another vector.
This method calculates a normalized vector that points from self to other. If self and other are the same vector,
resulting in a zero-length vector, None is returned.
§Arguments
other: The target vector to which the direction is calculated.
§Returns
An Option<Self> where:
Some(Self)contains the normalized direction vector pointing fromselftootherif the vectors are not identical.Noneifselfandotherare identical (i.e., the direction vector has zero length).
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let vec1 = Vec2::new(1.0, 2.0);
let vec2 = Vec2::new(4.0, 6.0);
if let Some(direction) = vec1.direction(&vec2) {
assert_eq!(direction, Vec2::new(0.6, 0.8));
} else {
panic!("The vectors are identical, so no direction can be computed.");
}Sourcepub fn angle(&self, other: &Self) -> T
pub fn angle(&self, other: &Self) -> T
Computes the angle (in radians) between this vector and another vector.
This method calculates the angle between self and other vectors using the arctangent of the cross product
and dot product of the vectors. The result is in radians, and the angle is measured counterclockwise.
§Arguments
other: The other vector to which the angle is computed.
§Returns
The angle between the vectors as a value of type T.
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let vec1 = Vec2::new(1.0, 0.0);
let vec2 = Vec2::new(0.0, 1.0);
assert_eq!(vec1.angle(&vec2), std::f32::consts::PI / 2.0);Sourcepub fn line_angle(&self, end: &Self) -> T
pub fn line_angle(&self, end: &Self) -> T
Computes the angle (in radians) of the line defined by two vectors.
This method calculates the angle of the line segment defined by self and end relative to the positive x-axis.
The vectors should be normalized for accurate results. The angle is measured from the positive x-axis to the line,
and the result is in radians. The direction is clockwise from the positive x-axis.
§Arguments
end: The end point of the line segment fromselftoend.
§Returns
The angle of the line segment as a value of type T.
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let start = Vec2::new(1.0, 1.0);
let end = Vec2::new(4.0, 3.0);
assert_eq!(start.line_angle(&end), (-0.6435011).abs()); // Example resultSourcepub fn lerp(&self, other: &Self, t: T) -> Self
pub fn lerp(&self, other: &Self, t: T) -> Self
Linearly interpolates between this vector and another vector.
This method performs linear interpolation between self and other based on the parameter t.
When t is 0.0, the result is self. When t is 1.0, the result is other. For values of t
between 0.0 and 1.0, the result is a point between self and other on the line segment connecting them.
§Arguments
other: The vector to interpolate towards.t: The interpolation factor, wheretranges from0.0to1.0.
§Returns
A new vector representing the point that is linearly interpolated between self and other.
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let start = Vec2::new(0.0, 0.0);
let end = Vec2::new(10.0, 10.0);
let result = start.lerp(&end, 0.5);
assert_eq!(result, Vec2::new(5.0, 5.0));Sourcepub fn reflect(&self, normal: &Self) -> Self
pub fn reflect(&self, normal: &Self) -> Self
Computes the reflection of the vector around a given normal vector.
The reflection is calculated using the formula:
reflected = self - 2 * (self · normal) * normal
where self · normal is the dot product between self and normal.
§Parameters
normal: The normal vector around which to reflect. This vector should be normalized.
§Returns
A new vector representing the reflection of self around normal.
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Example
let incident = Vec2::new(1.0, -1.0);
let normal = Vec2::new(0.0, 1.0).normalize().unwrap(); // Normalized normal vector
let reflected = incident.reflect(&normal);
assert_eq!(reflected, Vec2::new(1.0, 1.0)); // Reflection of (1.0, -1.0) around (0.0, 1.0) is (1.0, 1.0)Sourcepub fn refract(&self, normal: &Self, r: T) -> Option<Self>
pub fn refract(&self, normal: &Self, r: T) -> Option<Self>
Computes the direction of a refracted ray.
This function calculates the direction of a refracted ray given the direction of the incoming ray, the normal vector of the surface, and the ratio of the refractive indices of the two media.
§Parameters
normal: The normalized normal vector of the interface between two optical media.r: The ratio of the refractive index of the medium from where the ray comes to the refractive index of the medium on the other side of the surface.
§Returns
An Option<Self>. Returns Some(Self) with the direction of the refracted ray if refraction is possible,
or None if refraction is not possible (e.g., due to total internal reflection).
§Constraints
Tmust implement theFloattrait, which provides methods for floating-point arithmetic.
§Notes
- The incoming ray and the normal vector should be normalized.
- The result will be
Noneif total internal reflection occurs (i.e.,d < 0).
Sourcepub fn rotate(&self, angle: T) -> Self
pub fn rotate(&self, angle: T) -> Self
Rotates the vector by a given angle (in radians) around the origin.
This method applies a 2D rotation to the vector, rotating it by the specified angle in a counterclockwise direction around the origin (0, 0).
§Arguments
angle- The angle of rotation in radians. A positive angle rotates the vector counterclockwise, while a negative angle rotates it clockwise.
§Returns
A new vector that represents the original vector rotated by the specified angle.
§Examples
let v = Vec2::new(1.0, 0.0);
let rotated_v = v.rotate(std::f32::consts::PI / 2.0);
assert_eq!(rotated_v, Vec2::new(0.0, 1.0));Sourcepub fn move_towards(&self, target: &Self, max_distance: T) -> Self
pub fn move_towards(&self, target: &Self, max_distance: T) -> Self
Moves the vector towards a target vector by a specified maximum distance.
This method calculates the direction from the vector to a target vector and moves the vector along that direction by a specified maximum distance. If the target vector is closer than the specified distance, the vector will be moved directly to the target position.
§Arguments
target- The target vector to move towards.max_distance- The maximum distance to move. If this distance is greater than the distance to the target, the vector will move directly to the target.
§Returns
A new vector that represents the original vector moved towards the target by the specified distance.
§Examples
let start = Vec2::new(1.0, 1.0);
let target = Vec2::new(4.0, 5.0);
let result = start.move_towards(&target, 2.0);
// result will be a vector closer to the target by 2.0 units.Sourcepub fn recip(&self) -> Self
pub fn recip(&self) -> Self
Computes the reciprocal (1/x) of each component of the vector.
This method returns a new vector where each component is the reciprocal of the corresponding component of the original vector. This is equivalent to element-wise division of 1 by the vector components.
§Returns
A new vector where each component is the reciprocal of the corresponding component of the original vector.
§Panics
This method will panic if any component of the vector is zero, as the reciprocal of zero is undefined and would result in a division by zero error.
§Examples
let v = Vec2::new(2.0, 4.0);
let recip_v = v.recip();
assert_eq!(recip_v, Vec2::new(0.5, 0.25));Trait Implementations§
Source§impl<T> AddAssign for Vec2<T>
impl<T> AddAssign for Vec2<T>
Source§fn add_assign(&mut self, other: Self)
fn add_assign(&mut self, other: Self)
+= operation. Read moreSource§impl<T> AddAssign<T> for Vec2<T>
impl<T> AddAssign<T> for Vec2<T>
Source§fn add_assign(&mut self, scalar: T)
fn add_assign(&mut self, scalar: T)
+= operation. Read moreimpl<T: Copy> Copy for Vec2<T>
Source§impl<T> DivAssign for Vec2<T>
impl<T> DivAssign for Vec2<T>
Source§fn div_assign(&mut self, other: Self)
fn div_assign(&mut self, other: Self)
/= operation. Read moreSource§impl<T> DivAssign<T> for Vec2<T>
impl<T> DivAssign<T> for Vec2<T>
Source§fn div_assign(&mut self, scalar: T)
fn div_assign(&mut self, scalar: T)
/= operation. Read moreSource§impl<'a, T> IntoIterator for &'a Vec2<T>
impl<'a, T> IntoIterator for &'a Vec2<T>
Source§impl<'a, T> IntoIterator for &'a mut Vec2<T>
impl<'a, T> IntoIterator for &'a mut Vec2<T>
Source§impl<T> MulAssign for Vec2<T>
impl<T> MulAssign for Vec2<T>
Source§fn mul_assign(&mut self, other: Self)
fn mul_assign(&mut self, other: Self)
*= operation. Read moreSource§impl<T> MulAssign<T> for Vec2<T>
impl<T> MulAssign<T> for Vec2<T>
Source§fn mul_assign(&mut self, scalar: T)
fn mul_assign(&mut self, scalar: T)
*= operation. Read more