A game about forced loneliness, made by TACStudios
1using System;
2using System.Collections.Generic;
3
4namespace UnityEngine.TestTools.Utils
5{
6 /// <summary>
7 /// Use this class to compare two Vector2 objects for
8 /// equality with NUnit constraints. Use the static
9 /// <see cref="Vector2EqualityComparer.Instance"/>
10 /// to have the calculation error value set to default 0.0001f.
11 /// For any other error value, instantiate a new comparer
12 /// object with the one argument constructor.
13 /// </summary>
14 public class Vector2EqualityComparer : IEqualityComparer<Vector2>
15 {
16 private const float k_DefaultError = 0.0001f;
17 private readonly float AllowedError;
18
19 private static readonly Vector2EqualityComparer m_Instance = new Vector2EqualityComparer();
20
21 /// <summary>
22 /// A comparer instance with the default error value set to 0.0001f.
23 ///</summary>
24 public static Vector2EqualityComparer Instance { get { return m_Instance; } }
25
26 private Vector2EqualityComparer() : this(k_DefaultError)
27 {
28 }
29 /// <summary>
30 /// Initializes an instance of Vector2Equality comparer with custom allowed calculation error.
31 /// </summary>
32 /// <param name="error">This value identifies the calculation error allowed.</param>
33 public Vector2EqualityComparer(float error)
34 {
35 AllowedError = error;
36 }
37
38 /// <summary>
39 /// Compares the actual and expected Vector2 objects for equality using the <see cref="Utils.AreFloatsEqual"/> method.
40 /// </summary>
41 /// <param name="expected">The expected Vector2 used for comparison</param>
42 /// <param name="actual">The actual Vector2 to test</param>
43 /// <returns>True if the vectors are equals, false otherwise.</returns>
44 /// <example>
45 /// The following example shows how to verify if two Vector2 are equals
46 ///<code>
47 ///[TestFixture]
48 /// public class Vector2Test
49 /// {
50 /// [Test]
51 /// public void VerifyThat_TwoVector2ObjectsAreEqual()
52 /// {
53 /// // Custom calculation error
54 /// var actual = new Vector2(10e-7f, 10e-7f);
55 /// var expected = new Vector2(0f, 0f);
56 /// var comparer = new Vector2EqualityComparer(10e-6f);
57 ///
58 /// Assert.That(actual, Is.EqualTo(expected).Using(comparer));
59 ///
60 /// //Default error 0.0001f
61 /// actual = new Vector2(0.01f, 0.01f);
62 /// expected = new Vector2(0.01f, 0.01f);
63 ///
64 /// Assert.That(actual, Is.EqualTo(expected).Using(Vector2EqualityComparer.Instance));
65 /// }
66 /// }
67 /// </code>
68 /// </example>
69 public bool Equals(Vector2 expected, Vector2 actual)
70 {
71 return Utils.AreFloatsEqual(expected.x, actual.x, AllowedError) &&
72 Utils.AreFloatsEqual(expected.y, actual.y, AllowedError);
73 }
74
75 /// <summary>
76 /// Serves as the default hash function.
77 /// </summary>
78 /// <param name="vec2">A not null Vector2</param>
79 /// <returns>Returns 0</returns>
80 public int GetHashCode(Vector2 vec2)
81 {
82 return 0;
83 }
84 }
85}