Skip to content
Snippets Groups Projects
directionality.rs 1.78 KiB
Newer Older
Louis's avatar
Louis committed
use std::fmt::{Display, Formatter};

use bevy::math::{Vec2, Vec3};
use bevy::prelude::Component;

#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Horizontal {
	Left,
	#[default]
	Right,
}

impl From<f32> for Horizontal {
	fn from(other: f32) -> Self {
		if other < 0.0 {
			Self::Left
		} else {
			Self::Right
		}
	}
}

impl Display for Horizontal {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		match self {
			Horizontal::Left => f.write_str("left"),
			Horizontal::Right => f.write_str("right"),
		}
	}
}

#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Vertical {
	Up,
	#[default]
	Down,
}

impl From<f32> for Vertical {
	fn from(other: f32) -> Self {
		if other < 0.0 {
			Self::Up
		} else {
			Self::Down
		}
	}
}

impl Display for Vertical {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		match self {
			Vertical::Up => f.write_str("up"),
			Vertical::Down => f.write_str("down"),
		}
	}
}

#[derive(Clone, Debug, Component, PartialEq, Eq, Ord, PartialOrd, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Directionality {
	pub vertical: Vertical,
	pub horizontal: Horizontal,
}

impl From<Vec2> for Directionality {
	fn from(other: Vec2) -> Self {
		Self {
			horizontal: other.x.into(),
			vertical: other.y.into(),
		}
	}
}

impl From<Vec3> for Directionality {
	fn from(other: Vec3) -> Self {
		Self {
			horizontal: other.x.into(),
			vertical: other.y.into(),
		}
	}
}

impl Display for Directionality {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}_{}", self.horizontal, self.vertical)
	}
}