From 72eb7189be3f5530589c408f3e338a078207ee78 Mon Sep 17 00:00:00 2001 From: Corwin Date: Wed, 15 May 2024 18:30:03 +0100 Subject: [PATCH] add dot and cross product --- agb-fixnum/src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/agb-fixnum/src/lib.rs b/agb-fixnum/src/lib.rs index 6b75318f..e9f427b6 100644 --- a/agb-fixnum/src/lib.rs +++ b/agb-fixnum/src/lib.rs @@ -1113,6 +1113,48 @@ impl Vector2D { } } + #[doc(alias = "scalar_product")] + /// Calculates the dot product / scalar product of two vectors + /// ``` + /// use agb_fixnum::Vector2D; + /// + /// let v1 = Vector2D::new(3, 5); + /// let v2 = Vector2D::new(7, 11); + /// + /// let dot = v1.dot(v2); + /// assert_eq!(dot, 76); + /// ``` + /// The dot product for vectors *A* and *B* is defined as + /// > *A**x* × *B**x* + *A**y* × *B**y*. + pub fn dot(self, b: Self) -> T { + self.x * b.x + self.y * b.y + } + + #[doc(alias = "vector_product")] + /// Calculates the *z* component of the cross product / vector product of two + /// vectors + /// ``` + /// use agb_fixnum::Vector2D; + /// + /// let v1 = Vector2D::new(3, 5); + /// let v2 = Vector2D::new(7, 11); + /// + /// let dot = v1.cross(v2); + /// assert_eq!(dot, -2); + /// ``` + /// The cross product for vectors *A* and *B* is defined as + /// > *A**x* × *B**y* - *A**y* × *B**x*. + /// + /// + /// Normally the cross product / vector product is itself a vector. This is + /// in the 3D case where the cross product of two vectors is perpendicular + /// to both vectors. The only vector perpendicular to two 2D vectors is + /// purely in the *z* direction, hence why this method only returns that + /// component. The *x* and *y* components are always zero. + pub fn cross(self, b: Self) -> T { + self.x * b.y - self.y * b.x + } + #[must_use] /// Swaps the x and y coordinate /// ```