6个版本
| 0.2.0 | 2024年4月3日 | 
|---|---|
| 0.1.4 | 2024年4月3日 | 
#642 in 数学
在 simple_3d_vector 中使用
18KB
446 行
简单二维向量
Rust中的简单基于网格的二维向量
入门
要开始使用 simple_2d_vector,请使用 cargo add simple_2d_vector 将其添加到您的项目中。
然后,您可以使用提供的 Vector2D 结构体使用它。
示例
使用 Vector2D::new() 创建一个 Vector2D 并将其与 Vector2D::null() 进行比较
use vector2d::Vector2D;
fn main() {
    let vector = Vector2D::new(
        (0.0, 0.0), // The origin of the vector
        (0.0, 0.0)  // The target of the vector
    );
    
    // Null vectors are vectors with a length of zero
    // They are also called zero-length vectors as they only have an origin
    let null_vector = Vector2D::null((0.0, 0.0)); // A null vector
    
    assert_eq!(vector, null_vector); // The two vectors are the same
}
使用向量执行加法和减法
use vector2d::Vector2D;
fn main() { 
    let vector1 = Vector2D::new(
        (10.0, 10.0), 
        (10.0, 5.0)
    );
    
    let vector2 = Vector2D::new(
        (10.0, 10.0), 
        (5.0, 10.0)
    );
    
    let result_vector_addition = Vector2D::new(
        (10.0, 10.0), 
        (15.0, 15.0)
    );
    
    let result_vector_subtraction = Vector2D::new(
        (10.0, 10.0), 
        (5.0, -5.0)
    );
    
    assert_eq!(vector1 + vector2, result_vector_addition);
    assert_eq!(vector1 - vector2, result_vector_subtraction);
}
移动向量
use vector2d::Vector2D;
fn main() { 
    let vector = Vector2D::new(
        (10.0, 10.0), 
        (10.0, 5.0)
    );
    
    // `Vector2D.shift` automatically converts applicable types into f32
    let shift = (-2i16, 1.25); // This allows for a mismatch of types
    
    // Shifting a vector moves only its `origin`,
    // as it's `target` is relative to its `origin`
    let result_vector = Vector2D::new(
        (8.0, 11.25), 
        (10.0, 5.0)
    );
    
    assert_eq!(vector.shift(shift), result_vector);
}