Add possibly useful conversions.

This commit is contained in:
Nolan Darilek 2021-06-08 10:10:59 -05:00
parent 08e6c4779a
commit eefd3a2209

View File

@ -1,7 +1,7 @@
use std::{ use std::{
cmp::{max, min}, cmp::{max, min},
fmt::Display, fmt::Display,
ops::Sub, ops::{Add, AddAssign, Sub, SubAssign},
}; };
use bevy::{core::FloatOrd, prelude::*, transform::TransformSystem}; use bevy::{core::FloatOrd, prelude::*, transform::TransformSystem};
@ -13,6 +13,75 @@ use rand::prelude::*;
#[reflect(Component)] #[reflect(Component)]
pub struct Coordinates(pub (f32, f32)); pub struct Coordinates(pub (f32, f32));
impl Coordinates {
pub fn from_transform(transform: &Transform, config: &CoreConfig) -> Self {
Self((
transform.x() / config.pixels_per_unit as f32,
transform.y() / config.pixels_per_unit as f32,
))
}
fn to_transform(&self, config: &CoreConfig) -> Transform {
Transform::from_translation(Vec3::new(
self.0 .0 * config.pixels_per_unit as f32,
self.0 .1 * config.pixels_per_unit as f32,
0.,
))
}
}
impl Add for Coordinates {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self((self.0 .0 + rhs.0 .0, self.0 .1 + rhs.0 .1))
}
}
impl AddAssign for Coordinates {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs
}
}
impl Sub for Coordinates {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self((self.0 .0 - rhs.0 .0, self.0 .1 - rhs.0 .1))
}
}
impl SubAssign for Coordinates {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs
}
}
impl From<Vec2> for Coordinates {
fn from(v: Vec2) -> Self {
Self((v.x, v.y))
}
}
impl From<Vec3> for Coordinates {
fn from(v: Vec3) -> Self {
Self((v.x, v.y))
}
}
impl From<Coordinates> for Vec2 {
fn from(c: Coordinates) -> Self {
Vec2::new(c.0 .0, c.0 .1)
}
}
impl From<Coordinates> for Vec3 {
fn from(c: Coordinates) -> Self {
Vec3::new(c.0 .0, c.0 .1, 0.)
}
}
impl From<(f32, f32)> for Coordinates { impl From<(f32, f32)> for Coordinates {
fn from(v: (f32, f32)) -> Self { fn from(v: (f32, f32)) -> Self {
Coordinates((v.0, v.1)) Coordinates((v.0, v.1))