【从头写CAD】矢量类

//* 编制人: $ource
//* 修改版次及创建时间:0版完成版(2024年8月15日)
//* 修改内容及时间:无
//* 待完善问题:错误捕获未核实对错
use std::ops::{Add, Sub, Mul, Div};
use super::angle::Angle;
#[derive(Debug,PartialEq,PartialOrd)]
pub struct Vector2D{
    x:f64, y:f64
}

impl Vector2D{
    // 构造函数(double,double),(double,Angle)
    pub fn new(x:f64, y:f64)->Vector2D{
        Vector2D{x:x,y:y}
    }
    pub fn polar(distance:f64, angle:Angle)->Vector2D{
        Vector2D{x:distance * angle.x() , y:distance * angle.x()}
    }

    pub fn get_x(&self)->f64{
        self.x
    }

    pub fn get_y(&self)->f64{
        self.y
    }

    // 判断原点属性
    pub fn is_empty(&self)->bool{
        self.x == 0.0 && self.y == 0.0//未考虑实数计算舍入偏差
    }
     // 极坐标属性
    pub fn distance(&self)->f64{
        (self.x * self.x + self.y * self.y).sqrt()
    }
    pub fn set_distance(& mut self,d:f64){
        if self.y == 0f64 {
            self.x = d;//保证原Distance!=0
        }else{
            let dd=d / self.distance();
            self.x =self.x*dd;
            self.y=self.y*dd
        } 
    }
    pub fn angle(&self)->Angle{
        Angle::from(self.x,self.y)
    }

    pub fn set_angle(&mut self,angle:Angle){
        let d=self.distance();
        self.x=angle.x() *d;
        self.y=angle.y() *d;
    }

}

//运算符重载 + - * /,实现加减及比例缩放
impl Add for Vector2D{
    type Output = Self;
    fn add(self, other: Self) -> Self {
        Self{x:self.x + other.x , y:self.y + other.y}
    }
}

impl Sub for Vector2D{
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        Self{x:self.x - other.x , y:self.y - other.y}
    }
}
 // 若 P × Q > 0 , 则P在Q的顺时针方向。//若 P × Q < 0 , 则P在Q的逆时针方向。//若 P × Q = 0 , 则P与Q共线,但可能同向也可能反向。
impl Mul for Vector2D{
    type Output = f64;
    fn mul(self, other: Self) -> f64 {
        self.x * other.y - self.y * other.x
    }
}

impl Mul<f64> for Vector2D{
    type Output = Self;
    fn mul(self, scale: f64) -> Vector2D {
        Vector2D{x:self.x * scale, y:self.y * scale}
    }
}

impl Div<f64> for Vector2D{
    type Output = Self;
    fn div(self, scale: f64) -> Vector2D {
        Vector2D::new(self.x / scale, self.y / scale)
    }
}

impl Mul<Angle> for Vector2D{
    type Output = Self;
    fn mul(self, angle: Angle) -> Vector2D {
         Vector2D::polar(self.distance(),self.angle()+angle)
    }
}

impl Div<Angle> for Vector2D{
    type Output = Self;
    fn div(self, angle: Angle) -> Vector2D {
        Vector2D::polar(self.distance(),self.angle()-angle)
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值