Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

Added 'inverse()' to 'Vector2'.

Edward Chanc76791def25c
diff --git a/core/math/vector2.h b/core/math/vector2.h
index 622ea2cb59b..86479a6799d 100644
--- a/core/math/vector2.h
+++ b/core/math/vector2.h
@@ -88,6 +88,10 @@ struct [[nodiscard]] Vector2 {
Vector2 normalized() const;
bool is_normalized() const;
+ _FORCE_INLINE_ Vector2 inverse() const {
+ return Vector2(1.0f / x, 1.0f / y);
+ }
+
real_t length() const;
real_t length_squared() const;
Vector2 limit_length(real_t p_len = 1.0) const;
diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp
index fa1b3d6d053..a850c23c5bd 100644
--- a/core/variant/variant_call.cpp
+++ b/core/variant/variant_call.cpp
@@ -2118,6 +2118,7 @@ static void _register_variant_builtin_methods_math() {
bind_method(Vector2, is_equal_approx, sarray("to"), varray());
bind_method(Vector2, is_zero_approx, sarray(), varray());
bind_method(Vector2, is_finite, sarray(), varray());
+ bind_method(Vector2, inverse, sarray(), varray());
bind_method(Vector2, posmod, sarray("mod"), varray());
bind_method(Vector2, posmodv, sarray("modv"), varray());
bind_method(Vector2, project, sarray("b"), varray());
diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml
index cdb32d36aee..fbf51fc92ba 100644
--- a/doc/classes/Vector2.xml
+++ b/doc/classes/Vector2.xml
@@ -221,6 +221,12 @@
[b]Note:[/b] The length of the returned [Vector2] is [i]approximately[/i] [code]1.0[/code], but is is not guaranteed to be exactly [code]1.0[/code] due to floating-point precision issues. Call [method normalized] on the returned [Vector2] if you require a unit vector.
</description>
</method>
+ <method name="inverse" qualifiers="const">
+ <return type="Vector2" />
+ <description>
+ Returns the inverse of the vector. This is the same as [code]Vector2(1.0 / v.x, 1.0 / v.y)[/code].
+ </description>
+ </method>
<method name="is_equal_approx" qualifiers="const">
<return type="bool" />
<param index="0" name="to" type="Vector2" />
diff --git a/tests/core/math/test_vector2.cpp b/tests/core/math/test_vector2.cpp
index 75c80b43d16..399d9d9d56e 100644
--- a/tests/core/math/test_vector2.cpp
+++ b/tests/core/math/test_vector2.cpp
@@ -304,6 +304,10 @@ TEST_CASE("[Vector2] Other methods") {
Vector2(1, 1).direction_to(Vector2(2, 2)).is_equal_approx(Vector2(Math::SQRT12, Math::SQRT12)),
"Vector2 direction_to should work as expected.");
+ CHECK_MESSAGE(
+ vector.inverse().is_equal_approx(Vector2(1 / 1.2, 1 / 3.4)),
+ "Vector2 inverse should work as expected.");
+
CHECK_MESSAGE(
vector.posmod(2).is_equal_approx(Vector2(1.2, 1.4)),
"Vector2 posmod should work as expected.");