iced-yoda/core/src/point.rs

78 lines
1.5 KiB
Rust
Raw Normal View History

use crate::Vector;
2019-08-28 06:45:39 +02:00
/// A 2D point.
2020-04-28 03:06:35 +02:00
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Point {
2019-08-31 06:20:56 +02:00
/// The X coordinate.
pub x: f32,
2019-08-31 06:20:56 +02:00
/// The Y coordinate.
pub y: f32,
}
impl Point {
2020-04-02 02:20:14 +02:00
/// The origin (i.e. a [`Point`] at (0, 0)).
2020-02-14 04:59:31 +01:00
///
/// [`Point`]: struct.Point.html
pub const ORIGIN: Point = Point::new(0.0, 0.0);
/// Creates a new [`Point`] with the given coordinates.
///
/// [`Point`]: struct.Point.html
2020-02-14 04:59:31 +01:00
pub const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
/// Computes the distance to another [`Point`].
///
/// [`Point`]: struct.Point.html
pub fn distance(&self, to: Point) -> f32 {
let a = self.x - to.x;
let b = self.y - to.y;
2020-03-20 04:08:18 +01:00
a.hypot(b)
}
}
impl From<[f32; 2]> for Point {
fn from([x, y]: [f32; 2]) -> Self {
Point { x, y }
}
}
impl From<[u16; 2]> for Point {
fn from([x, y]: [u16; 2]) -> Self {
Point::new(x.into(), y.into())
}
}
impl std::ops::Add<Vector> for Point {
type Output = Self;
fn add(self, vector: Vector) -> Self {
Self {
x: self.x + vector.x,
y: self.y + vector.y,
}
}
}
2020-03-07 23:45:54 +01:00
impl std::ops::Sub<Vector> for Point {
type Output = Self;
fn sub(self, vector: Vector) -> Self {
Self {
x: self.x - vector.x,
y: self.y - vector.y,
}
}
}
impl std::ops::Sub<Point> for Point {
type Output = Vector;
fn sub(self, point: Point) -> Vector {
Vector::new(self.x - point.x, self.y - point.y)
}
}