From 52443bfa68361c4263d7441d5bb531b130c57ce4 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Mon, 10 Aug 2020 02:16:35 +0200 Subject: [PATCH] added some more utility functions for directions and vectors --- MLEM/Extensions/NumberExtensions.cs | 16 ++++++++++++++++ MLEM/Misc/Direction2.cs | 15 +++++++++++++++ Sandbox/GameImpl.cs | 7 +++++++ 3 files changed, 38 insertions(+) diff --git a/MLEM/Extensions/NumberExtensions.cs b/MLEM/Extensions/NumberExtensions.cs index d25365f..3fd4db6 100644 --- a/MLEM/Extensions/NumberExtensions.cs +++ b/MLEM/Extensions/NumberExtensions.cs @@ -59,6 +59,21 @@ namespace MLEM.Extensions { return new Vector4(vec.X.Floor(), vec.Y.Floor(), vec.Z.Floor(), vec.W.Floor()); } + /// + public static Vector2 CeilCopy(this Vector2 vec) { + return new Vector2(vec.X.Ceil(), vec.Y.Ceil()); + } + + /// + public static Vector3 CeilCopy(this Vector3 vec) { + return new Vector3(vec.X.Ceil(), vec.Y.Ceil(), vec.Z.Ceil()); + } + + /// + public static Vector4 CeilCopy(this Vector4 vec) { + return new Vector4(vec.X.Ceil(), vec.Y.Ceil(), vec.Z.Ceil(), vec.W.Ceil()); + } + /// /// Multiplies a point by a given scalar. /// @@ -184,5 +199,6 @@ namespace MLEM.Extensions { matrix.M31 / scZ, matrix.M32 / scZ, matrix.M33 / scZ, 0, 0, 0, 0, 1)); } + } } \ No newline at end of file diff --git a/MLEM/Misc/Direction2.cs b/MLEM/Misc/Direction2.cs index b685fc8..790b575 100644 --- a/MLEM/Misc/Direction2.cs +++ b/MLEM/Misc/Direction2.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; +using MLEM.Extensions; namespace MLEM.Misc { /// @@ -229,5 +230,19 @@ namespace MLEM.Misc { } } + /// + /// Returns the that is closest to the given position's facing direction. + /// + /// The vector whose corresponding direction to get + /// The vector's direction + public static Direction2 ToDirection(this Vector2 offset) { + var offsetAngle = (float) Math.Atan2(offset.Y, offset.X); + foreach (var dir in AllExceptNone) { + if (Math.Abs(dir.Angle() - offsetAngle) <= MathHelper.PiOver4 / 2) + return dir; + } + return Direction2.None; + } + } } \ No newline at end of file diff --git a/Sandbox/GameImpl.cs b/Sandbox/GameImpl.cs index 6c0ee56..d130701 100644 --- a/Sandbox/GameImpl.cs +++ b/Sandbox/GameImpl.cs @@ -100,6 +100,13 @@ namespace Sandbox { }; Console.WriteLine(obj); + for (var i = 0; i < 360; i += 45) { + var rad = MathHelper.ToRadians(i); + var vec = new Vector2((float) Math.Sin(rad), (float) Math.Cos(rad)); + var dir = vec.ToDirection(); + Console.WriteLine(vec + " -> " + dir); + } + var copy = obj.DeepCopy(); Console.WriteLine(copy);