//* 编制人: $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)
}
}
【从头写CAD】矢量类
于 2024-08-15 17:44:30 首次发布