diff --git a/classes/class_animation.rst b/classes/class_animation.rst index 4d37c7df8..c977ca1a2 100644 --- a/classes/class_animation.rst +++ b/classes/class_animation.rst @@ -1347,7 +1347,7 @@ Sets the value of an existing key. |void| **track_set_path**\ (\ track_idx\: :ref:`int`, path\: :ref:`NodePath`\ ) :ref:`🔗` -Sets the path of a track. Paths must be valid scene-tree paths to a node and must be specified starting from the parent node of the node that will reproduce the animation. Tracks that control properties or bones must append their name after the path, separated by ``":"``. +Sets the path of a track. Paths must be valid scene-tree paths to a node and must be specified starting from the :ref:`AnimationMixer.root_node` that will reproduce the animation. Tracks that control properties or bones must append their name after the path, separated by ``":"``. For example, ``"character/skeleton:ankle"`` or ``"character/mesh:transform/local"``. diff --git a/classes/class_animationmixer.rst b/classes/class_animationmixer.rst index e654fedda..42d15af41 100644 --- a/classes/class_animationmixer.rst +++ b/classes/class_animationmixer.rst @@ -454,9 +454,9 @@ This makes it more convenient to preview and edit animations in the editor, as c - |void| **set_root_motion_track**\ (\ value\: :ref:`NodePath`\ ) - :ref:`NodePath` **get_root_motion_track**\ (\ ) -The path to the Animation track used for root motion. Paths must be valid scene-tree paths to a node, and must be specified starting from the parent node of the node that will reproduce the animation. To specify a track that controls properties or bones, append its name after the path, separated by ``":"``. For example, ``"character/skeleton:ankle"`` or ``"character/mesh:transform/local"``. +The path to the Animation track used for root motion. Paths must be valid scene-tree paths to a node, and must be specified starting from the parent node of the node that will reproduce the animation. The :ref:`root_motion_track` uses the same format as :ref:`Animation.track_set_path`, but note that a bone must be specified. -If the track has type :ref:`Animation.TYPE_POSITION_3D`, :ref:`Animation.TYPE_ROTATION_3D` or :ref:`Animation.TYPE_SCALE_3D` the transformation will be canceled visually, and the animation will appear to stay in place. See also :ref:`get_root_motion_position`, :ref:`get_root_motion_rotation`, :ref:`get_root_motion_scale` and :ref:`RootMotionView`. +If the track has type :ref:`Animation.TYPE_POSITION_3D`, :ref:`Animation.TYPE_ROTATION_3D`, or :ref:`Animation.TYPE_SCALE_3D` the transformation will be canceled visually, and the animation will appear to stay in place. See also :ref:`get_root_motion_position`, :ref:`get_root_motion_rotation`, :ref:`get_root_motion_scale`, and :ref:`RootMotionView`. .. rst-class:: classref-item-separator diff --git a/classes/class_array.rst b/classes/class_array.rst index 450bbd976..aba6bcbb5 100644 --- a/classes/class_array.rst +++ b/classes/class_array.rst @@ -17,7 +17,7 @@ A built-in data structure that holds a sequence of elements. Description ----------- -An array data structure that can contain a sequence of elements of any type. Elements are accessed by a numerical index starting at 0. Negative indices are used to count from the back (-1 is the last element, -2 is the second to last, etc.). +An array data structure that can contain a sequence of elements of any :ref:`Variant` type. Elements are accessed by a numerical index starting at 0. Negative indices are used to count from the back (-1 is the last element, -2 is the second to last, etc.). \ **Example:**\ @@ -26,45 +26,29 @@ An array data structure that can contain a sequence of elements of any type. Ele .. code-tab:: gdscript - var array = ["One", 2, 3, "Four"] - print(array[0]) # One. - print(array[2]) # 3. - print(array[-1]) # Four. - array[2] = "Three" - print(array[-2]) # Three. + var array = ["First", 2, 3, "Last"] + print(array[0]) # Prints "First" + print(array[2]) # Prints 3 + print(array[-1]) # Prints "Last" + + array[1] = "Second" + print(array[1]) # Prints "Second" + print(array[-3]) # Prints "Second" .. code-tab:: csharp - var array = new Godot.Collections.Array{"One", 2, 3, "Four"}; - GD.Print(array[0]); // One. - GD.Print(array[2]); // 3. - GD.Print(array[array.Count - 1]); // Four. - array[2] = "Three"; - GD.Print(array[array.Count - 2]); // Three. + var array = new Godot.Collections.Array{"First", 2, 3, "Last"}; + GD.Print(array[0]); // Prints "First" + GD.Print(array[2]); // Prints 3 + GD.Print(array[array.Count - 1]); // Prints "Last" + + array[2] = "Second"; + GD.Print(array[1]); // Prints "Second" + GD.Print(array[array.Count - 3]); // Prints "Second" -Arrays can be concatenated using the ``+`` operator: - - -.. tabs:: - - .. code-tab:: gdscript - - var array1 = ["One", 2] - var array2 = [3, "Four"] - print(array1 + array2) # ["One", 2, 3, "Four"] - - .. code-tab:: csharp - - // Array concatenation is not possible with C# arrays, but is with Godot.Collections.Array. - var array1 = new Godot.Collections.Array{"One", 2}; - var array2 = new Godot.Collections.Array{3, "Four"}; - GD.Print(array1 + array2); // Prints [One, 2, 3, Four] - - - -\ **Note:** Arrays are always passed by reference. To get a copy of an array that can be modified independently of the original array, use :ref:`duplicate`. +\ **Note:** Arrays are always passed by **reference**. To get a copy of an array that can be modified independently of the original array, use :ref:`duplicate`. \ **Note:** Erasing elements while iterating over arrays is **not** supported and will result in unpredictable behavior. @@ -263,37 +247,41 @@ Constructs an empty **Array**. :ref:`Array` **Array**\ (\ base\: :ref:`Array`, type\: :ref:`int`, class_name\: :ref:`StringName`, script\: :ref:`Variant`\ ) -Creates a typed array from the ``base`` array. All arguments are required. +Creates a typed array from the ``base`` array. A typed array can only contain elements of the given type, or that inherit from the given class, as described by this constructor's parameters: -- ``type`` is the built-in type as a :ref:`Variant.Type` constant, for example :ref:`@GlobalScope.TYPE_INT`. +- ``type`` is the built-in :ref:`Variant` type, as one the :ref:`Variant.Type` constants. -- ``class_name`` is the **native** class name, for example :ref:`Node`. If ``type`` is not :ref:`@GlobalScope.TYPE_OBJECT`, must be an empty string. +- ``class_name`` is the built-in class name (see :ref:`Object.get_class`). -- ``script`` is the associated script. Must be a :ref:`Script` instance or ``null``. +- ``script`` is the associated script. It must be a :ref:`Script` instance or ``null``. -Examples: +If ``type`` is not :ref:`@GlobalScope.TYPE_OBJECT`, ``class_name`` must be an empty :ref:`StringName` and ``script`` must be ``null``. :: - class_name MyNode + class_name Sword extends Node - class MyClass: + class Stats: pass func _ready(): - var a = Array([], TYPE_INT, &"", null) # Array[int] - var b = Array([], TYPE_OBJECT, &"Node", null) # Array[Node] - var c = Array([], TYPE_OBJECT, &"Node", MyNode) # Array[MyNode] - var d = Array([], TYPE_OBJECT, &"RefCounted", MyClass) # Array[MyClass] + var a = Array([], TYPE_INT, "", null) # Array[int] + var b = Array([], TYPE_OBJECT, "Node", null) # Array[Node] + var c = Array([], TYPE_OBJECT, "Node", Sword) # Array[Sword] + var d = Array([], TYPE_OBJECT, "RefCounted", Stats) # Array[Stats] -\ **Note:** This constructor can be useful if you want to create a typed array on the fly, but you are not required to use it. In GDScript you can use a temporary variable with the static type you need and then pass it: +The ``base`` array's elements are converted when necessary. If this is not possible or ``base`` is already typed, this constructor fails and returns an empty **Array**. + +In GDScript, this constructor is usually not necessary, as it is possible to create a typed array through static typing: :: - func _ready(): - var a: Array[int] = [] - some_func(a) + var numbers: Array[float] = [] + var children: Array[Node] = [$Node, $Sprite2D, $RigidBody3D] + + var integers: Array[int] = [0.2, 4.5, -2.0] + print(integers) # Prints [0, 4, -2] .. rst-class:: classref-item-separator @@ -420,22 +408,50 @@ Method Descriptions :ref:`bool` **all**\ (\ method\: :ref:`Callable`\ ) |const| :ref:`🔗` -Calls the provided :ref:`Callable` on each element in the array and returns ``true`` if the :ref:`Callable` returns ``true`` for *all* elements in the array. If the :ref:`Callable` returns ``false`` for one array element or more, this method returns ``false``. +Calls the given :ref:`Callable` on each element in the array and returns ``true`` if the :ref:`Callable` returns ``true`` for *all* elements in the array. If the :ref:`Callable` returns ``false`` for one array element or more, this method returns ``false``. -The callable's method should take one :ref:`Variant` parameter (the current array element) and return a boolean value. +The ``method`` should take one :ref:`Variant` parameter (the current array element) and return a :ref:`bool`. -:: - func _ready(): - print([6, 10, 6].all(greater_than_5)) # Prints True (3/3 elements evaluate to `true`). - print([4, 10, 4].all(greater_than_5)) # Prints False (1/3 elements evaluate to `true`). - print([4, 4, 4].all(greater_than_5)) # Prints False (0/3 elements evaluate to `true`). - print([].all(greater_than_5)) # Prints True (0/0 elements evaluate to `true`). - - print([6, 10, 6].all(func(number): return number > 5)) # Prints True. Same as the first line above, but using lambda function. - +.. tabs:: + + .. code-tab:: gdscript + func greater_than_5(number): return number > 5 + + func _ready(): + print([6, 10, 6].all(greater_than_5)) # Prints true (3/3 elements evaluate to true). + print([4, 10, 4].all(greater_than_5)) # Prints false (1/3 elements evaluate to true). + print([4, 4, 4].all(greater_than_5)) # Prints false (0/3 elements evaluate to true). + print([].all(greater_than_5)) # Prints true (0/0 elements evaluate to true). + + # Same as the first line above, but using a lambda function. + print([6, 10, 6].all(func(element): return element > 5)) # Prints true + + .. code-tab:: csharp + + private static bool GreaterThan5(int number) + { + return number > 5; + } + + public override void _Ready() + { + // Prints true (3/3 elements evaluate to true). + GD.Print(new Godot.Collections.Array>int< { 6, 10, 6 }.All(GreaterThan5)); + // Prints false (1/3 elements evaluate to true). + GD.Print(new Godot.Collections.Array>int< { 4, 10, 4 }.All(GreaterThan5)); + // Prints false (0/3 elements evaluate to true). + GD.Print(new Godot.Collections.Array>int< { 4, 4, 4 }.All(GreaterThan5)); + // Prints true (0/0 elements evaluate to true). + GD.Print(new Godot.Collections.Array>int< { }.All(GreaterThan5)); + + // Same as the first line above, but using a lambda function. + GD.Print(new Godot.Collections.Array>int< { 6, 10, 6 }.All(element => element > 5)); // Prints true + } + + See also :ref:`any`, :ref:`filter`, :ref:`map` and :ref:`reduce`. @@ -453,22 +469,23 @@ See also :ref:`any`, :ref:`filter` **any**\ (\ method\: :ref:`Callable`\ ) |const| :ref:`🔗` -Calls the provided :ref:`Callable` on each element in the array and returns ``true`` if the :ref:`Callable` returns ``true`` for *one or more* elements in the array. If the :ref:`Callable` returns ``false`` for all elements in the array, this method returns ``false``. +Calls the given :ref:`Callable` on each element in the array and returns ``true`` if the :ref:`Callable` returns ``true`` for *one or more* elements in the array. If the :ref:`Callable` returns ``false`` for all elements in the array, this method returns ``false``. -The callable's method should take one :ref:`Variant` parameter (the current array element) and return a boolean value. +The ``method`` should take one :ref:`Variant` parameter (the current array element) and return a :ref:`bool`. :: - func _ready(): - print([6, 10, 6].any(greater_than_5)) # Prints True (3 elements evaluate to `true`). - print([4, 10, 4].any(greater_than_5)) # Prints True (1 elements evaluate to `true`). - print([4, 4, 4].any(greater_than_5)) # Prints False (0 elements evaluate to `true`). - print([].any(greater_than_5)) # Prints False (0 elements evaluate to `true`). - - print([6, 10, 6].any(func(number): return number > 5)) # Prints True. Same as the first line above, but using lambda function. - func greater_than_5(number): return number > 5 + + func _ready(): + print([6, 10, 6].any(greater_than_5)) # Prints true (3 elements evaluate to true). + print([4, 10, 4].any(greater_than_5)) # Prints true (1 elements evaluate to true). + print([4, 4, 4].any(greater_than_5)) # Prints false (0 elements evaluate to true). + print([].any(greater_than_5)) # Prints false (0 elements evaluate to true). + + # Same as the first line above, but using a lambda function. + print([6, 10, 6].any(func(number): return number > 5)) # Prints true See also :ref:`all`, :ref:`filter`, :ref:`map` and :ref:`reduce`. @@ -486,7 +503,7 @@ See also :ref:`all`, :ref:`filter`\ ) :ref:`🔗` -Appends an element at the end of the array (alias of :ref:`push_back`). +Appends ``value`` at the end of the array (alias of :ref:`push_back`). .. rst-class:: classref-item-separator @@ -498,14 +515,14 @@ Appends an element at the end of the array (alias of :ref:`push_back`\ ) :ref:`🔗` -Appends another array at the end of this array. +Appends another ``array`` at the end of this array. :: - var array1 = [1, 2, 3] - var array2 = [4, 5, 6] - array1.append_array(array2) - print(array1) # Prints [1, 2, 3, 4, 5, 6]. + var numbers = [1, 2, 3] + var extra = [4, 5, 6] + numbers.append_array(extra) + print(nums) # Prints [1, 2, 3, 4, 5, 6] .. rst-class:: classref-item-separator @@ -529,9 +546,9 @@ Assigns elements of another ``array`` into the array. Resizes the array to match :ref:`Variant` **back**\ (\ ) |const| :ref:`🔗` -Returns the last element of the array. Prints an error and returns ``null`` if the array is empty. +Returns the last element of the array. If the array is empty, fails and returns ``null``. See also :ref:`front`. -\ **Note:** Calling this function is not the same as writing ``array[-1]``. If the array is empty, accessing by index will pause project execution when running from the editor. +\ **Note:** Unlike with the ``[]`` operator (``array[-1]``), an error is generated without stopping project execution. .. rst-class:: classref-item-separator @@ -543,15 +560,23 @@ Returns the last element of the array. Prints an error and returns ``null`` if t :ref:`int` **bsearch**\ (\ value\: :ref:`Variant`, before\: :ref:`bool` = true\ ) |const| :ref:`🔗` -Finds the index of an existing value (or the insertion index that maintains sorting order, if the value is not yet present in the array) using binary search. Optionally, a ``before`` specifier can be passed. If ``false``, the returned index comes after all existing entries of the value in the array. +Returns the index of ``value`` in the sorted array. If it cannot be found, returns where ``value`` should be inserted to keep the array sorted. The algorithm used is `binary search `__. + +If ``before`` is ``true`` (as by default), the returned index comes before all existing elements equal to ``value`` in the array. :: - var array = ["a", "b", "c", "c", "d", "e"] - print(array.bsearch("c", true)) # Prints 2, at the first matching element. - print(array.bsearch("c", false)) # Prints 4, after the last matching element, pointing to "d". + var numbers = [2, 4, 8, 10] + var idx = numbers.bsearch(7) + + numbers.insert(idx, 7) + print(numbers) # Prints [2, 4, 7, 8, 10] + + var fruits = ["Apple", "Lemon", "Lemon", "Orange"] + print(fruits.bsearch("Lemon", true)) # Prints 1, points at the first "Lemon". + print(fruits.bsearch("Lemon", false)) # Prints 3, points at "Orange". -\ **Note:** Calling :ref:`bsearch` on an unsorted array results in unexpected behavior. +\ **Note:** Calling :ref:`bsearch` on an *unsorted* array will result in unexpected behavior. Use :ref:`sort` before calling this method. .. rst-class:: classref-item-separator @@ -563,11 +588,34 @@ Finds the index of an existing value (or the insertion index that maintains sort :ref:`int` **bsearch_custom**\ (\ value\: :ref:`Variant`, func\: :ref:`Callable`, before\: :ref:`bool` = true\ ) |const| :ref:`🔗` -Finds the index of an existing value (or the insertion index that maintains sorting order, if the value is not yet present in the array) using binary search and a custom comparison method. Optionally, a ``before`` specifier can be passed. If ``false``, the returned index comes after all existing entries of the value in the array. The custom method receives two arguments (an element from the array and the value searched for) and must return ``true`` if the first argument is less than the second, and return ``false`` otherwise. +Returns the index of ``value`` in the sorted array. If it cannot be found, returns where ``value`` should be inserted to keep the array sorted (using ``func`` for the comparisons). The algorithm used is `binary search `__. -\ **Note:** The custom method must accept the two arguments in any order, you cannot rely on that the first argument will always be from the array. +Similar to :ref:`sort_custom`, ``func`` is called as many times as necessary, receiving one array element and ``value`` as arguments. The function should return ``true`` if the array element should be *behind* ``value``, otherwise it should return ``false``. -\ **Note:** Calling :ref:`bsearch_custom` on an unsorted array results in unexpected behavior. +If ``before`` is ``true`` (as by default), the returned index comes before all existing elements equal to ``value`` in the array. + +:: + + func sort_by_amount(a, b): + if a[1] < b[1]: + return true + return false + + func _ready(): + var my_items = [["Tomato", 2], ["Kiwi", 5], ["Rice", 9]] + + var apple = ["Apple", 5] + # "Apple" is inserted before "Kiwi". + my_items.insert(my_items.bsearch_custom(apple, sort_by_amount, true), apple) + + var banana = ["Banana", 5] + # "Banana" is inserted after "Kiwi". + my_items.insert(my_items.bsearch_custom(banana, sort_by_amount, false), banana) + + # Prints [["Tomato", 2], ["Apple", 5], ["Kiwi", 5], ["Banana", 5], ["Rice", 9]] + print(my_items) + +\ **Note:** Calling :ref:`bsearch_custom` on an *unsorted* array will result in unexpected behavior. Use :ref:`sort_custom` with ``func`` before calling this method. .. rst-class:: classref-item-separator @@ -579,7 +627,7 @@ Finds the index of an existing value (or the insertion index that maintains sort |void| **clear**\ (\ ) :ref:`🔗` -Clears the array. This is equivalent to using :ref:`resize` with a size of ``0``. +Removes all elements from the array. This is equivalent to using :ref:`resize` with a size of ``0``. .. rst-class:: classref-item-separator @@ -603,9 +651,11 @@ Returns the number of times an element is in the array. :ref:`Array` **duplicate**\ (\ deep\: :ref:`bool` = false\ ) |const| :ref:`🔗` -Returns a copy of the array. +Returns a new copy of the array. -If ``deep`` is ``true``, a deep copy is performed: all nested arrays and dictionaries are duplicated and will not be shared with the original array. If ``false``, a shallow copy is made and references to the original nested arrays and dictionaries are kept, so that modifying a sub-array or dictionary in the copy will also impact those referenced in the source array. Note that any :ref:`Object`-derived elements will be shallow copied regardless of the ``deep`` setting. +By default, a **shallow** copy is returned: all nested **Array** and :ref:`Dictionary` elements are shared with the original array. Modifying them in one array will also affect them in the other. + +If ``deep`` is ``true``, a **deep** copy is returned: all nested arrays and dictionaries are also duplicated (recursively). .. rst-class:: classref-item-separator @@ -617,13 +667,11 @@ If ``deep`` is ``true``, a deep copy is performed: all nested arrays and diction |void| **erase**\ (\ value\: :ref:`Variant`\ ) :ref:`🔗` -Removes the first occurrence of a value from the array. If the value does not exist in the array, nothing happens. To remove an element by index, use :ref:`remove_at` instead. +Finds and removes the first occurrence of ``value`` from the array. If ``value`` does not exist in the array, nothing happens. To remove an element by index, use :ref:`remove_at` instead. -\ **Note:** This method acts in-place and doesn't return a modified array. +\ **Note:** This method shifts every element's index after the removed ``value`` back, which may have a noticeable performance cost, especially on larger arrays. -\ **Note:** On large arrays, this method will be slower if the removed element is close to the beginning of the array (index 0). This is because all elements placed after the removed element have to be reindexed. - -\ **Note:** Do not erase entries while iterating over the array. +\ **Note:** Erasing elements while iterating over arrays is **not** supported and will result in unpredictable behavior. .. rst-class:: classref-item-separator @@ -635,7 +683,9 @@ Removes the first occurrence of a value from the array. If the value does not ex |void| **fill**\ (\ value\: :ref:`Variant`\ ) :ref:`🔗` -Assigns the given value to all elements in the array. This can typically be used together with :ref:`resize` to create an array with a given size and initialized elements: +Assigns the given ``value`` to all elements in the array. + +This method can often be combined with :ref:`resize` to create an array with a given size and initialized elements: .. tabs:: @@ -643,18 +693,20 @@ Assigns the given value to all elements in the array. This can typically be used .. code-tab:: gdscript var array = [] - array.resize(10) - array.fill(0) # Initialize the 10 elements to 0. + array.resize(5) + array.fill(2) + print(array) # Prints [2, 2, 2, 2, 2] .. code-tab:: csharp var array = new Godot.Collections.Array(); - array.Resize(10); - array.Fill(0); // Initialize the 10 elements to 0. + array.Resize(5); + array.Fill(2); + GD.Print(array); // Prints [2, 2, 2, 2, 2] -\ **Note:** If ``value`` is of a reference type (:ref:`Object`-derived, **Array**, :ref:`Dictionary`, etc.) then the array is filled with the references to the same object, i.e. no duplicates are created. +\ **Note:** If ``value`` is a :ref:`Variant` passed by reference (:ref:`Object`-derived, **Array**, :ref:`Dictionary`, etc.), the array will be filled with references to the same ``value``, which are not duplicates. .. rst-class:: classref-item-separator @@ -666,18 +718,20 @@ Assigns the given value to all elements in the array. This can typically be used :ref:`Array` **filter**\ (\ method\: :ref:`Callable`\ ) |const| :ref:`🔗` -Calls the provided :ref:`Callable` on each element in the array and returns a new array with the elements for which the method returned ``true``. +Calls the given :ref:`Callable` on each element in the array and returns a new, filtered **Array**. -The callable's method should take one :ref:`Variant` parameter (the current array element) and return a boolean value. +The ``method`` receives one of the array elements as an argument, and should return ``true`` to add the element to the filtered array, or ``false`` to exclude it. :: - func _ready(): - print([1, 2, 3].filter(remove_1)) # Prints [2, 3]. - print([1, 2, 3].filter(func(number): return number != 1)) # Same as above, but using lambda function. + func is_even(number): + return number % 2 == 0 - func remove_1(number): - return number != 1 + func _ready(): + print([1, 4, 5, 8].filter(is_even)) # Prints [4, 8] + + # Same as above, but using a lambda function. + print([1, 4, 5, 8].filter(func(number): return number % 2 == 0)) See also :ref:`any`, :ref:`all`, :ref:`map` and :ref:`reduce`. @@ -691,7 +745,11 @@ See also :ref:`any`, :ref:`all`, :ref:`int` **find**\ (\ what\: :ref:`Variant`, from\: :ref:`int` = 0\ ) |const| :ref:`🔗` -Searches the array for a value and returns its index or ``-1`` if not found. Optionally, the initial search index can be passed. +Returns the index of the **first** occurrence of ``what`` in this array, or ``-1`` if there are none. The search's start can be specified with ``from``, continuing to the end of the array. + +\ **Note:** If you just want to know whether the array contains ``what``, use :ref:`has` (``Contains`` in C#). In GDScript, you may also use the ``in`` operator. + +\ **Note:** For performance reasons, the search is affected by ``what``'s :ref:`Variant.Type`. For example, ``7`` (:ref:`int`) and ``7.0`` (:ref:`float`) are not considered equal for this method. .. rst-class:: classref-item-separator @@ -703,9 +761,9 @@ Searches the array for a value and returns its index or ``-1`` if not found. Opt :ref:`Variant` **front**\ (\ ) |const| :ref:`🔗` -Returns the first element of the array. Prints an error and returns ``null`` if the array is empty. +Returns the first element of the array. If the array is empty, fails and returns ``null``. See also :ref:`back`. -\ **Note:** Calling this function is not the same as writing ``array[0]``. If the array is empty, accessing by index will pause project execution when running from the editor. +\ **Note:** Unlike with the ``[]`` operator (``array[0]``), an error is generated without stopping project execution. .. rst-class:: classref-item-separator @@ -717,7 +775,7 @@ Returns the first element of the array. Prints an error and returns ``null`` if :ref:`int` **get_typed_builtin**\ (\ ) |const| :ref:`🔗` -Returns the built-in type of the typed array as a :ref:`Variant.Type` constant. If the array is not typed, returns :ref:`@GlobalScope.TYPE_NIL`. +Returns the built-in :ref:`Variant` type of the typed array as a :ref:`Variant.Type` constant. If the array is not typed, returns :ref:`@GlobalScope.TYPE_NIL`. See also :ref:`is_typed`. .. rst-class:: classref-item-separator @@ -729,7 +787,7 @@ Returns the built-in type of the typed array as a :ref:`Variant.Type` **get_typed_class_name**\ (\ ) |const| :ref:`🔗` -Returns the **native** class name of the typed array if the built-in type is :ref:`@GlobalScope.TYPE_OBJECT`. Otherwise, this method returns an empty string. +Returns the **built-in** class name of the typed array, if the built-in :ref:`Variant` type :ref:`@GlobalScope.TYPE_OBJECT`. Otherwise, returns an empty :ref:`StringName`. See also :ref:`is_typed` and :ref:`Object.get_class`. .. rst-class:: classref-item-separator @@ -741,7 +799,7 @@ Returns the **native** class name of the typed array if the built-in type is :re :ref:`Variant` **get_typed_script**\ (\ ) |const| :ref:`🔗` -Returns the script associated with the typed array. This method returns a :ref:`Script` instance or ``null``. +Returns the :ref:`Script` instance associated with this typed array, or ``null`` if it does not exist. See also :ref:`is_typed`. .. rst-class:: classref-item-separator @@ -753,50 +811,37 @@ Returns the script associated with the typed array. This method returns a :ref:` :ref:`bool` **has**\ (\ value\: :ref:`Variant`\ ) |const| :ref:`🔗` -Returns ``true`` if the array contains the given value. +Returns ``true`` if the array contains the given ``value``. .. tabs:: .. code-tab:: gdscript - print(["inside", 7].has("inside")) # True - print(["inside", 7].has("outside")) # False - print(["inside", 7].has(7)) # True - print(["inside", 7].has("7")) # False + print(["inside", 7].has("inside")) # Prints true + print(["inside", 7].has("outside")) # Prints false + print(["inside", 7].has(7)) # Prints true + print(["inside", 7].has("7")) # Prints false .. code-tab:: csharp var arr = new Godot.Collections.Array { "inside", 7 }; - // has is renamed to Contains - GD.Print(arr.Contains("inside")); // True - GD.Print(arr.Contains("outside")); // False - GD.Print(arr.Contains(7)); // True - GD.Print(arr.Contains("7")); // False + // By C# convention, this method is renamed to `Contains`. + GD.Print(arr.Contains("inside")); // Prints true + GD.Print(arr.Contains("outside")); // Prints false + GD.Print(arr.Contains(7)); // Prints true + GD.Print(arr.Contains("7")); // Prints false -\ **Note:** This is equivalent to using the ``in`` operator as follows: +In GDScript, this is equivalent to the ``in`` operator: +:: -.. tabs:: - - .. code-tab:: gdscript - - # Will evaluate to `true`. - if 2 in [2, 4, 6, 8]: - print("Contains!") - - .. code-tab:: csharp - - // As there is no "in" keyword in C#, you have to use Contains - var array = new Godot.Collections.Array { 2, 4, 6, 8 }; - if (array.Contains(2)) - { - GD.Print("Contains!"); - } - + if 4 in [2, 4, 6, 8]: + print("4 is here!") # Will be printed. +\ **Note:** For performance reasons, the search is affected by the ``value``'s :ref:`Variant.Type`. For example, ``7`` (:ref:`int`) and ``7.0`` (:ref:`float`) are not considered equal for this method. .. rst-class:: classref-item-separator @@ -810,7 +855,7 @@ Returns ``true`` if the array contains the given value. Returns a hashed 32-bit integer value representing the array and its contents. -\ **Note:** **Array**\ s with equal content will always produce identical hash values. However, the reverse is not true. Returning identical hash values does *not* imply the arrays are equal, because different arrays can have identical hash values due to hash collisions. +\ **Note:** Arrays with equal hash values are *not* guaranteed to be the same, as a result of hash collisions. On the countrary, arrays with different hash values are guaranteed to be different. .. rst-class:: classref-item-separator @@ -822,11 +867,11 @@ Returns a hashed 32-bit integer value representing the array and its contents. :ref:`int` **insert**\ (\ position\: :ref:`int`, value\: :ref:`Variant`\ ) :ref:`🔗` -Inserts a new element at a given position in the array. The position must be valid, or at the end of the array (``pos == size()``). Returns :ref:`@GlobalScope.OK` on success, or one of the other :ref:`Error` values if the operation failed. +Inserts a new element (``value``) at a given index (``position``) in the array. ``position`` should be between ``0`` and the array's :ref:`size`. -\ **Note:** This method acts in-place and doesn't return a modified array. +Returns :ref:`@GlobalScope.OK` on success, or one of the other :ref:`Error` constants if this method fails. -\ **Note:** On large arrays, this method will be slower if the inserted element is close to the beginning of the array (index 0). This is because all elements placed after the newly inserted element have to be reindexed. +\ **Note:** Every element's index after ``position`` needs to be shifted forward, which may have a noticeable performance cost, especially on larger arrays. .. rst-class:: classref-item-separator @@ -838,7 +883,7 @@ Inserts a new element at a given position in the array. The position must be val :ref:`bool` **is_empty**\ (\ ) |const| :ref:`🔗` -Returns ``true`` if the array is empty. +Returns ``true`` if the array is empty (``[]``). See also :ref:`size`. .. rst-class:: classref-item-separator @@ -850,7 +895,9 @@ Returns ``true`` if the array is empty. :ref:`bool` **is_read_only**\ (\ ) |const| :ref:`🔗` -Returns ``true`` if the array is read-only. See :ref:`make_read_only`. Arrays are automatically read-only if declared with ``const`` keyword. +Returns ``true`` if the array is read-only. See :ref:`make_read_only`. + +In GDScript, arrays are automatically read-only if declared with the ``const`` keyword. .. rst-class:: classref-item-separator @@ -862,7 +909,7 @@ Returns ``true`` if the array is read-only. See :ref:`make_read_only` **is_same_typed**\ (\ array\: :ref:`Array`\ ) |const| :ref:`🔗` -Returns ``true`` if the array is typed the same as ``array``. +Returns ``true`` if this array is typed the same as the given ``array``. See also :ref:`is_typed`. .. rst-class:: classref-item-separator @@ -874,7 +921,14 @@ Returns ``true`` if the array is typed the same as ``array``. :ref:`bool` **is_typed**\ (\ ) |const| :ref:`🔗` -Returns ``true`` if the array is typed. Typed arrays can only store elements of their associated type and provide type safety for the ``[]`` operator. Methods of typed array still return :ref:`Variant`. +Returns ``true`` if the array is typed. Typed arrays can only contain elements of a specific type, as defined by the typed array constructor. The methods of a typed array are still expected to return a generic :ref:`Variant`. + +In GDScript, it is possible to define a typed array with static typing: + +:: + + var numbers: Array[float] = [0.2, 4.2, -2.0] + print(numbers.is_typed()) # Prints true .. rst-class:: classref-item-separator @@ -886,7 +940,9 @@ Returns ``true`` if the array is typed. Typed arrays can only store elements of |void| **make_read_only**\ (\ ) :ref:`🔗` -Makes the array read-only, i.e. disabled modifying of the array's elements. Does not apply to nested content, e.g. content of nested arrays. +Makes the array read-only. The array's elements cannot be overridden with different values, and their order cannot change. Does not apply to nested elements, such as dictionaries. + +In GDScript, arrays are automatically read-only if declared with the ``const`` keyword. .. rst-class:: classref-item-separator @@ -898,18 +954,20 @@ Makes the array read-only, i.e. disabled modifying of the array's elements. Does :ref:`Array` **map**\ (\ method\: :ref:`Callable`\ ) |const| :ref:`🔗` -Calls the provided :ref:`Callable` for each element in the array and returns a new array filled with values returned by the method. +Calls the given :ref:`Callable` for each element in the array and returns a new array filled with values returned by the ``method``. -The callable's method should take one :ref:`Variant` parameter (the current array element) and can return any :ref:`Variant`. +The ``method`` should take one :ref:`Variant` parameter (the current array element) and can return any :ref:`Variant`. :: - func _ready(): - print([1, 2, 3].map(negate)) # Prints [-1, -2, -3]. - print([1, 2, 3].map(func(number): return -number)) # Same as above, but using lambda function. + func double(number): + return number * 2 - func negate(number): - return -number + func _ready(): + print([1, 2, 3].map(double)) # Prints [2, 4, 6] + + # Same as above, but using a lambda function. + print([1, 2, 3].map(func(element): return element * 2)) See also :ref:`filter`, :ref:`reduce`, :ref:`any` and :ref:`all`. @@ -923,19 +981,9 @@ See also :ref:`filter`, :ref:`reduce` **max**\ (\ ) |const| :ref:`🔗` -Returns the maximum value contained in the array if all elements are of comparable types. If the elements can't be compared, ``null`` is returned. +Returns the maximum value contained in the array, if all elements can be compared. Otherwise, returns ``null``. See also :ref:`min`. -To find the maximum value using a custom comparator, you can use :ref:`reduce`. In this example every array element is checked and the first maximum value is returned: - -:: - - func _ready(): - var arr = [Vector2(0, 1), Vector2(2, 0), Vector2(1, 1), Vector2(1, 0), Vector2(0, 2)] - # In this example we compare the lengths. - print(arr.reduce(func(max, val): return val if is_length_greater(val, max) else max)) - - func is_length_greater(a, b): - return a.length() > b.length() +To find the maximum value using a custom comparator, you can use :ref:`reduce`. .. rst-class:: classref-item-separator @@ -947,9 +995,7 @@ To find the maximum value using a custom comparator, you can use :ref:`reduce` **min**\ (\ ) |const| :ref:`🔗` -Returns the minimum value contained in the array if all elements are of comparable types. If the elements can't be compared, ``null`` is returned. - -See also :ref:`max` for an example of using a custom comparator. +Returns the minimum value contained in the array, if all elements can be compared. Otherwise, returns ``null``. See also :ref:`max`. .. rst-class:: classref-item-separator @@ -961,23 +1007,25 @@ See also :ref:`max` for an example of using a custom com :ref:`Variant` **pick_random**\ (\ ) |const| :ref:`🔗` -Returns a random value from the target array. Prints an error and returns ``null`` if the array is empty. +Returns a random element from the array. Generates an error and returns ``null`` if the array is empty. .. tabs:: .. code-tab:: gdscript - var array: Array[int] = [1, 2, 3, 4] - print(array.pick_random()) # Prints either of the four numbers. + # May print 1, 2, 3.25, or "Hi". + print([1, 2, 3.25, "Hi"].pick_random()) .. code-tab:: csharp - var array = new Godot.Collections.Array { 1, 2, 3, 4 }; - GD.Print(array.PickRandom()); // Prints either of the four numbers. + var array = new Godot.Collections.Array { 1, 2, 3.25f, "Hi" }; + GD.Print(array.PickRandom()); // May print 1, 2, 3.25, or "Hi". +\ **Note:** Like many similar functions in the engine (such as :ref:`@GlobalScope.randi` or :ref:`shuffle`), this method uses a common, global random seed. To get a predictable outcome from this method, see :ref:`@GlobalScope.seed`. + .. rst-class:: classref-item-separator ---- @@ -988,9 +1036,9 @@ Returns a random value from the target array. Prints an error and returns ``null :ref:`Variant` **pop_at**\ (\ position\: :ref:`int`\ ) :ref:`🔗` -Removes and returns the element of the array at index ``position``. If negative, ``position`` is considered relative to the end of the array. Leaves the array unchanged and returns ``null`` if the array is empty or if it's accessed out of bounds. An error message is printed when the array is accessed out of bounds, but not when the array is empty. +Removes and returns the element of the array at index ``position``. If negative, ``position`` is considered relative to the end of the array. Returns ``null`` if the array is empty. If ``position`` is out of bounds, an error message is also generated. -\ **Note:** On large arrays, this method can be slower than :ref:`pop_back` as it will reindex the array's elements that are located after the removed element. The larger the array and the lower the index of the removed element, the slower :ref:`pop_at` will be. +\ **Note:** This method shifts every element's index after ``position`` back, which may have a noticeable performance cost, especially on larger arrays. .. rst-class:: classref-item-separator @@ -1002,7 +1050,7 @@ Removes and returns the element of the array at index ``position``. If negative, :ref:`Variant` **pop_back**\ (\ ) :ref:`🔗` -Removes and returns the last element of the array. Returns ``null`` if the array is empty, without printing an error message. See also :ref:`pop_front`. +Removes and returns the last element of the array. Returns ``null`` if the array is empty, without generating an error. See also :ref:`pop_front`. .. rst-class:: classref-item-separator @@ -1014,9 +1062,9 @@ Removes and returns the last element of the array. Returns ``null`` if the array :ref:`Variant` **pop_front**\ (\ ) :ref:`🔗` -Removes and returns the first element of the array. Returns ``null`` if the array is empty, without printing an error message. See also :ref:`pop_back`. +Removes and returns the first element of the array. Returns ``null`` if the array is empty, without generating an error. See also :ref:`pop_back`. -\ **Note:** On large arrays, this method is much slower than :ref:`pop_back` as it will reindex all the array's elements every time it's called. The larger the array, the slower :ref:`pop_front` will be. +\ **Note:** This method shifts every other element's index back, which may have a noticeable performance cost, especially on larger arrays. .. rst-class:: classref-item-separator @@ -1042,7 +1090,7 @@ Appends an element at the end of the array. See also :ref:`push_front`. -\ **Note:** On large arrays, this method is much slower than :ref:`push_back` as it will reindex all the array's elements every time it's called. The larger the array, the slower :ref:`push_front` will be. +\ **Note:** This method shifts every other element's index forward, which may have a noticeable performance cost, especially on larger arrays. .. rst-class:: classref-item-separator @@ -1054,18 +1102,34 @@ Adds an element at the beginning of the array. See also :ref:`push_back` **reduce**\ (\ method\: :ref:`Callable`, accum\: :ref:`Variant` = null\ ) |const| :ref:`🔗` -Calls the provided :ref:`Callable` for each element in array and accumulates the result in ``accum``. +Calls the given :ref:`Callable` for each element in array, accumulates the result in ``accum``, then returns it. -The callable's method takes two arguments: the current value of ``accum`` and the current array element. If ``accum`` is ``null`` (default value), the iteration will start from the second element, with the first one used as initial value of ``accum``. +The ``method`` takes two arguments: the current value of ``accum`` and the current array element. If ``accum`` is ``null`` (as by default), the iteration will start from the second element, with the first one used as initial value of ``accum``. + +:: + + func sum(accum, number): + return accum + number + + func _ready(): + print([1, 2, 3].reduce(sum, 0)) # Prints 6 + print([1, 2, 3].reduce(sum, 10)) # Prints 16 + + # Same as above, but using a lambda function. + print([1, 2, 3].reduce(func(accum, number): return accum + number, 10)) + +If :ref:`max` is not desirable, this method may also be used to implement a custom comparator: :: func _ready(): - print([1, 2, 3].reduce(sum, 10)) # Prints 16. - print([1, 2, 3].reduce(func(accum, number): return accum + number, 10)) # Same as above, but using lambda function. + var arr = [Vector2(5, 0), Vector2(3, 4), Vector2(1, 2)] - func sum(accum, number): - return accum + number + var longest_vec = arr.reduce(func(max, vec): return vec if is_length_greater(vec, max) else max) + print(longest_vec) # Prints Vector2(3, 4). + + func is_length_greater(a, b): + return a.length() > b.length() See also :ref:`map`, :ref:`filter`, :ref:`any` and :ref:`all`. @@ -1079,13 +1143,13 @@ See also :ref:`map`, :ref:`filter`\ ) :ref:`🔗` -Removes an element from the array by index. If the index does not exist in the array, nothing happens. To remove an element by searching for its value, use :ref:`erase` instead. +Removes the element from the array at the given index (``position``). If the index is out of bounds, this method fails. -\ **Note:** This method acts in-place and doesn't return a modified array. +If you need to return the removed element, use :ref:`pop_at`. To remove an element by value, use :ref:`erase` instead. -\ **Note:** On large arrays, this method will be slower if the removed element is close to the beginning of the array (index 0). This is because all elements placed after the removed element have to be reindexed. +\ **Note:** This method shifts every element's index after ``position`` back, which may have a noticeable performance cost, especially on larger arrays. -\ **Note:** ``position`` cannot be negative. To remove an element relative to the end of the array, use ``arr.remove_at(arr.size() - (i + 1))``. To remove the last element from the array without returning the value, use ``arr.resize(arr.size() - 1)``. +\ **Note:** The ``position`` cannot be negative. To remove an element relative to the end of the array, use ``arr.remove_at(arr.size() - (i + 1))``. To remove the last element from the array, use ``arr.resize(arr.size() - 1)``. .. rst-class:: classref-item-separator @@ -1097,11 +1161,11 @@ Removes an element from the array by index. If the index does not exist in the a :ref:`int` **resize**\ (\ size\: :ref:`int`\ ) :ref:`🔗` -Resizes the array to contain a different number of elements. If the array size is smaller, elements are cleared, if bigger, new elements are ``null``. Returns :ref:`@GlobalScope.OK` on success, or one of the other :ref:`Error` values if the operation failed. +Sets the array's number of elements to ``size``. If ``size`` is smaller than the array's current size, the elements at the end are removed. If ``size`` is greater, new default elements (usually ``null``) are added, depending on the array's type. -Calling :ref:`resize` once and assigning the new values is faster than adding new elements one by one. +Returns :ref:`@GlobalScope.OK` on success, or one of the other :ref:`Error` constants if this method fails. -\ **Note:** This method acts in-place and doesn't return a modified array. +\ **Note:** Calling this method once and assigning the new values is faster than calling :ref:`append` for every new element. .. rst-class:: classref-item-separator @@ -1113,7 +1177,7 @@ Calling :ref:`resize` once and assigning the new valu |void| **reverse**\ (\ ) :ref:`🔗` -Reverses the order of the elements in the array. +Reverses the order of all elements in the array. .. rst-class:: classref-item-separator @@ -1125,7 +1189,7 @@ Reverses the order of the elements in the array. :ref:`int` **rfind**\ (\ what\: :ref:`Variant`, from\: :ref:`int` = -1\ ) |const| :ref:`🔗` -Searches the array in reverse order. Optionally, a start search index can be passed. If negative, the start index is considered relative to the end of the array. +Returns the index of the **last** occurrence of ``what`` in this array, or ``-1`` if there are none. The search's start can be specified with ``from``, continuing to the beginning of the array. This method is the reverse of :ref:`find`. .. rst-class:: classref-item-separator @@ -1137,7 +1201,9 @@ Searches the array in reverse order. Optionally, a start search index can be pas |void| **shuffle**\ (\ ) :ref:`🔗` -Shuffles the array such that the items will have a random order. This method uses the global random number generator common to methods such as :ref:`@GlobalScope.randi`. Call :ref:`@GlobalScope.randomize` to ensure that a new seed will be used each time if you want non-reproducible shuffling. +Shuffles all elements of the array in a random order. + +\ **Note:** Like many similar functions in the engine (such as :ref:`@GlobalScope.randi` or :ref:`pick_random`), this method uses a common, global random seed. To get a predictable outcome from this method, see :ref:`@GlobalScope.seed`. .. rst-class:: classref-item-separator @@ -1149,7 +1215,7 @@ Shuffles the array such that the items will have a random order. This method use :ref:`int` **size**\ (\ ) |const| :ref:`🔗` -Returns the number of elements in the array. +Returns the number of elements in the array. Empty arrays (``[]``) always return ``0``. See also :ref:`is_empty`. .. rst-class:: classref-item-separator @@ -1161,17 +1227,24 @@ Returns the number of elements in the array. :ref:`Array` **slice**\ (\ begin\: :ref:`int`, end\: :ref:`int` = 2147483647, step\: :ref:`int` = 1, deep\: :ref:`bool` = false\ ) |const| :ref:`🔗` -Returns the slice of the **Array**, from ``begin`` (inclusive) to ``end`` (exclusive), as a new **Array**. +Returns a new **Array** containing this array's elements, from index ``begin`` (inclusive) to ``end`` (exclusive), every ``step`` elements. -The absolute value of ``begin`` and ``end`` will be clamped to the array size, so the default value for ``end`` makes it slice to the size of the array by default (i.e. ``arr.slice(1)`` is a shorthand for ``arr.slice(1, arr.size())``). +If either ``begin`` or ``end`` are negative, their value is relative to the end of the array. -If either ``begin`` or ``end`` are negative, they will be relative to the end of the array (i.e. ``arr.slice(0, -2)`` is a shorthand for ``arr.slice(0, arr.size() - 2)``). +If ``step`` is negative, this method iterates through the array in reverse, returning a slice ordered backwards. For this to work, ``begin`` must be greater than ``end``. -If specified, ``step`` is the relative index between source elements. It can be negative, then ``begin`` must be higher than ``end``. For example, ``[0, 1, 2, 3, 4, 5].slice(5, 1, -2)`` returns ``[5, 3]``. +If ``deep`` is ``true``, all nested **Array** and :ref:`Dictionary` elements in the slice are duplicated from the original, recursively. See also :ref:`duplicate`). -If ``deep`` is true, each element will be copied by value rather than by reference. +:: -\ **Note:** To include the first element when ``step`` is negative, use ``arr.slice(begin, -arr.size() - 1, step)`` (i.e. ``[0, 1, 2].slice(1, -4, -1)`` returns ``[1, 0]``). + var letters = ["A", "B", "C", "D", "E", "F"] + + print(letters.slice(0, 2)) # Prints ["A", "B"] + print(letters.slice(2, -2)) # Prints ["C", "D"] + print(letters.slice(-2, 6)) # Prints ["E", "F"] + + print(letters.slice(0, 6, 2)) # Prints ["A", "C", "E"] + print(letters.slice(4, 1, -1)) # Prints ["E", "D", "C"] .. rst-class:: classref-item-separator @@ -1183,36 +1256,26 @@ If ``deep`` is true, each element will be copied by value rather than by referen |void| **sort**\ (\ ) :ref:`🔗` -Sorts the array. - -\ **Note:** The sorting algorithm used is not `stable `__. This means that values considered equal may have their order changed when using :ref:`sort`. - -\ **Note:** Strings are sorted in alphabetical order (as opposed to natural order). This may lead to unexpected behavior when sorting an array of strings ending with a sequence of numbers. Consider the following example: +Sorts the array in ascending order. The final order is dependent on the "less than" (``>``) comparison between elements. .. tabs:: .. code-tab:: gdscript - var strings = ["string1", "string2", "string10", "string11"] - strings.sort() - print(strings) # Prints [string1, string10, string11, string2] + var numbers = [10, 5, 2.5, 8] + numbers.sort() + print(numbers) # Prints [2.5, 5, 8, 10] .. code-tab:: csharp - var strings = new Godot.Collections.Array { "string1", "string2", "string10", "string11" }; - strings.Sort(); - GD.Print(strings); // Prints [string1, string10, string11, string2] + var numbers = new Godot.Collections.Array { 10, 5, 2.5, 8 }; + numbers.Sort(); + GD.Print(numbers); // Prints [2.5, 5, 8, 10] -To perform natural order sorting, you can use :ref:`sort_custom` with :ref:`String.naturalnocasecmp_to` as follows: - -:: - - var strings = ["string1", "string2", "string10", "string11"] - strings.sort_custom(func(a, b): return a.naturalnocasecmp_to(b) < 0) - print(strings) # Prints [string1, string2, string10, string11] +\ **Note:** The sorting algorithm used is not `stable `__. This means that equivalent elements (such as ``2`` and ``2.0``) may have their order changed when calling :ref:`sort`. .. rst-class:: classref-item-separator @@ -1224,36 +1287,39 @@ To perform natural order sorting, you can use :ref:`sort_custom`\ ) :ref:`🔗` -Sorts the array using a custom method. The custom method receives two arguments (a pair of elements from the array) and must return either ``true`` or ``false``. For two elements ``a`` and ``b``, if the given method returns ``true``, element ``b`` will be after element ``a`` in the array. +Sorts the array using a custom :ref:`Callable`. -\ **Note:** The sorting algorithm used is not `stable `__. This means that values considered equal may have their order changed when using :ref:`sort_custom`. +\ ``func`` is called as many times as necessary, receiving two array elements as arguments. The function should return ``true`` if the first element should be moved *behind* the second one, otherwise it should return ``false``. -\ **Note:** You cannot randomize the return value as the heapsort algorithm expects a deterministic result. Randomizing the return value will result in unexpected behavior. - - -.. tabs:: - - .. code-tab:: gdscript +:: func sort_ascending(a, b): - if a[0] < b[0]: + if a[1] < b[1]: return true return false func _ready(): - var my_items = [[5, "Potato"], [9, "Rice"], [4, "Tomato"]] + var my_items = [["Tomato", 5], ["Apple", 9], ["Rice", 4]] my_items.sort_custom(sort_ascending) - print(my_items) # Prints [[4, Tomato], [5, Potato], [9, Rice]]. + print(my_items) # Prints [["Rice", 4], ["Tomato", 5], ["Apple", 9]] - # Descending, lambda version. + # Sort descending, using a lambda function. my_items.sort_custom(func(a, b): return a[0] > b[0]) - print(my_items) # Prints [[9, Rice], [5, Potato], [4, Tomato]]. + print(my_items) # Prints [["Apple", 9], ["Tomato", 5], ["Rice", 4]] - .. code-tab:: csharp +It may also be necessary to use this method to sort strings by natural order, with :ref:`String.naturalnocasecmp_to`, as in the following example: - // There is no custom sort support for Godot.Collections.Array +:: + var files = ["newfile1", "newfile2", "newfile10", "newfile11"] + files.sort_custom(func(a, b): return a.naturalnocasecmp_to(b) < 0) + print(files) # Prints ["newfile1", "newfile2", "newfile10", "newfile11"] +\ **Note:** In C#, this method is not supported. + +\ **Note:** The sorting algorithm used is not `stable `__. This means that values considered equal may have their order changed when calling this method. + +\ **Note:** You should not randomize the return value of ``func``, as the heapsort algorithm expects a consistent result. Randomizing the return value will result in unexpected behavior. .. rst-class:: classref-section-separator @@ -1270,7 +1336,7 @@ Operator Descriptions :ref:`bool` **operator !=**\ (\ right\: :ref:`Array`\ ) :ref:`🔗` -Compares the left operand **Array** against the ``right`` **Array**. Returns ``true`` if the sizes or contents of the arrays are *not* equal, ``false`` otherwise. +Returns ``true`` if the array's size or its elements are different than ``right``'s. .. rst-class:: classref-item-separator @@ -1282,7 +1348,27 @@ Compares the left operand **Array** against the ``right`` **Array**. Returns ``t :ref:`Array` **operator +**\ (\ right\: :ref:`Array`\ ) :ref:`🔗` -Concatenates two **Array**\ s together, with the ``right`` **Array** being added to the end of the **Array** specified in the left operand. For example, ``[1, 2] + [3, 4]`` results in ``[1, 2, 3, 4]``. +Appends the ``right`` array to the left operand, creating a new **Array**. This is also known as an array concatenation. + + +.. tabs:: + + .. code-tab:: gdscript + + var array1 = ["One", 2] + var array2 = [3, "Four"] + print(array1 + array2) # Prints ["One", 2, 3, "Four"] + + .. code-tab:: csharp + + // Note that concatenation is not possible with C#'s native Array type. + var array1 = new Godot.Collections.Array{"One", 2}; + var array2 = new Godot.Collections.Array{3, "Four"}; + GD.Print(array1 + array2); // Prints ["One", 2, 3, "Four"] + + + +\ **Note:** For existing arrays, :ref:`append_array` is much more efficient than concatenation and assignment with the ``+=`` operator. .. rst-class:: classref-item-separator @@ -1294,7 +1380,9 @@ Concatenates two **Array**\ s together, with the ``right`` **Array** being added :ref:`bool` **operator <**\ (\ right\: :ref:`Array`\ ) :ref:`🔗` -Performs a comparison for each index between the left operand **Array** and the ``right`` **Array**, considering the highest common index of both arrays for this comparison: Returns ``true`` on the first occurrence of an element that is less, or ``false`` if the element is greater. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns ``false`` if the left operand **Array** has fewer elements, otherwise it returns ``true``. +Compares the elements of both arrays in order, starting from index ``0`` and ending on the last index in common between both arrays. For each pair of elements, returns ``true`` if this array's element is less than ``right``'s, ``false`` if this element is greater. Otherwise, continues to the next pair. + +If all searched elements are equal, returns ``true`` if this array's size is less than ``right``'s, otherwise returns ``false``. .. rst-class:: classref-item-separator @@ -1306,7 +1394,9 @@ Performs a comparison for each index between the left operand **Array** and the :ref:`bool` **operator <=**\ (\ right\: :ref:`Array`\ ) :ref:`🔗` -Performs a comparison for each index between the left operand **Array** and the ``right`` **Array**, considering the highest common index of both arrays for this comparison: Returns ``true`` on the first occurrence of an element that is less, or ``false`` if the element is greater. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns ``true`` if the left operand **Array** has the same number of elements or fewer, otherwise it returns ``false``. +Compares the elements of both arrays in order, starting from index ``0`` and ending on the last index in common between both arrays. For each pair of elements, returns ``true`` if this array's element is less than ``right``'s, ``false`` if this element is greater. Otherwise, continues to the next pair. + +If all searched elements are equal, returns ``true`` if this array's size is less or equal to ``right``'s, otherwise returns ``false``. .. rst-class:: classref-item-separator @@ -1330,7 +1420,9 @@ Compares the left operand **Array** against the ``right`` **Array**. Returns ``t :ref:`bool` **operator >**\ (\ right\: :ref:`Array`\ ) :ref:`🔗` -Performs a comparison for each index between the left operand **Array** and the ``right`` **Array**, considering the highest common index of both arrays for this comparison: Returns ``true`` on the first occurrence of an element that is greater, or ``false`` if the element is less. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns ``true`` if the ``right`` **Array** has more elements, otherwise it returns ``false``. +Compares the elements of both arrays in order, starting from index ``0`` and ending on the last index in common between both arrays. For each pair of elements, returns ``true`` if this array's element is greater than ``right``'s, ``false`` if this element is less. Otherwise, continues to the next pair. + +If all searched elements are equal, returns ``true`` if this array's size is greater than ``right``'s, otherwise returns ``false``. .. rst-class:: classref-item-separator @@ -1342,7 +1434,9 @@ Performs a comparison for each index between the left operand **Array** and the :ref:`bool` **operator >=**\ (\ right\: :ref:`Array`\ ) :ref:`🔗` -Performs a comparison for each index between the left operand **Array** and the ``right`` **Array**, considering the highest common index of both arrays for this comparison: Returns ``true`` on the first occurrence of an element that is greater, or ``false`` if the element is less. Note that depending on the type of data stored, this function may be recursive. If all elements are equal, it compares the length of both arrays and returns ``true`` if the ``right`` **Array** has more or the same number of elements, otherwise it returns ``false``. +Compares the elements of both arrays in order, starting from index ``0`` and ending on the last index in common between both arrays. For each pair of elements, returns ``true`` if this array's element is greater than ``right``'s, ``false`` if this element is less. Otherwise, continues to the next pair. + +If all searched elements are equal, returns ``true`` if this array's size is greater or equal to ``right``'s, otherwise returns ``false``. .. rst-class:: classref-item-separator @@ -1354,7 +1448,7 @@ Performs a comparison for each index between the left operand **Array** and the :ref:`Variant` **operator []**\ (\ index\: :ref:`int`\ ) :ref:`🔗` -Returns a reference to the element of type :ref:`Variant` at the specified location. Arrays start at index 0. ``index`` can be a zero or positive value to start from the beginning, or a negative value to start from the end. Out-of-bounds array access causes a run-time error, which will result in an error being printed and the project execution pausing if run from the editor. +Returns the :ref:`Variant` element at the specified ``index``. Arrays start at index 0. If ``index`` is greater or equal to ``0``, the element is fetched starting from the beginning of the array. If ``index`` is a negative value, the element is fetched starting from the end. Accessing an array out-of-bounds will cause a run-time error, pausing the project execution if run from the editor. .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)` .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)` diff --git a/classes/class_editorexportplatformwindows.rst b/classes/class_editorexportplatformwindows.rst index d87b04a12..d9041fcaf 100644 --- a/classes/class_editorexportplatformwindows.rst +++ b/classes/class_editorexportplatformwindows.rst @@ -187,7 +187,7 @@ If set to ``1``, ANGLE libraries are exported with the exported application. If :ref:`int` **application/export_d3d12** :ref:`🔗` -If set to ``1``, Direct3D 12 runtime (DXIL, Agility SDK, PIX) libraries are exported with the exported application. If set to ``0``, Direct3D 12 libraries are exported only if :ref:`ProjectSettings.rendering/rendering_device/driver` is set to ``"d3d12"``. +If set to ``1``, the Direct3D 12 runtime libraries (Agility SDK, PIX) are exported with the exported application. If set to ``0``, Direct3D 12 libraries are exported only if :ref:`ProjectSettings.rendering/rendering_device/driver` is set to ``"d3d12"``. .. rst-class:: classref-item-separator diff --git a/classes/class_os.rst b/classes/class_os.rst index 1eca41e05..ae8e98be3 100644 --- a/classes/class_os.rst +++ b/classes/class_os.rst @@ -829,7 +829,7 @@ Returns the value of the given environment variable, or an empty string if ``var Returns the file path to the current engine executable. -\ **Note:** On macOS, always use :ref:`create_instance` instead of relying on executable path. +\ **Note:** On macOS, if you want to launch another instance of Godot, always use :ref:`create_instance` instead of relying on the executable path. .. rst-class:: classref-item-separator diff --git a/classes/class_physicspointqueryparameters2d.rst b/classes/class_physicspointqueryparameters2d.rst index 012764362..6544baca2 100644 --- a/classes/class_physicspointqueryparameters2d.rst +++ b/classes/class_physicspointqueryparameters2d.rst @@ -135,6 +135,8 @@ The physics layers the query will detect (as a bitmask). By default, all collisi The list of object :ref:`RID`\ s that will be excluded from collisions. Use :ref:`CollisionObject2D.get_rid` to get the :ref:`RID` associated with a :ref:`CollisionObject2D`-derived node. +\ **Note:** The returned array is copied and any changes to it will not update the original property value. To update the value you need to modify the returned array, and then assign it to the property again. + .. rst-class:: classref-item-separator ---- diff --git a/classes/class_physicspointqueryparameters3d.rst b/classes/class_physicspointqueryparameters3d.rst index 2f2765e9c..321305afa 100644 --- a/classes/class_physicspointqueryparameters3d.rst +++ b/classes/class_physicspointqueryparameters3d.rst @@ -114,6 +114,8 @@ The physics layers the query will detect (as a bitmask). By default, all collisi The list of object :ref:`RID`\ s that will be excluded from collisions. Use :ref:`CollisionObject3D.get_rid` to get the :ref:`RID` associated with a :ref:`CollisionObject3D`-derived node. +\ **Note:** The returned array is copied and any changes to it will not update the original property value. To update the value you need to modify the returned array, and then assign it to the property again. + .. rst-class:: classref-item-separator ---- diff --git a/classes/class_physicsrayqueryparameters2d.rst b/classes/class_physicsrayqueryparameters2d.rst index 4daa99ecb..1a8593ffa 100644 --- a/classes/class_physicsrayqueryparameters2d.rst +++ b/classes/class_physicsrayqueryparameters2d.rst @@ -130,6 +130,8 @@ The physics layers the query will detect (as a bitmask). By default, all collisi The list of object :ref:`RID`\ s that will be excluded from collisions. Use :ref:`CollisionObject2D.get_rid` to get the :ref:`RID` associated with a :ref:`CollisionObject2D`-derived node. +\ **Note:** The returned array is copied and any changes to it will not update the original property value. To update the value you need to modify the returned array, and then assign it to the property again. + .. rst-class:: classref-item-separator ---- diff --git a/classes/class_physicsrayqueryparameters3d.rst b/classes/class_physicsrayqueryparameters3d.rst index e53ca2eb1..990417768 100644 --- a/classes/class_physicsrayqueryparameters3d.rst +++ b/classes/class_physicsrayqueryparameters3d.rst @@ -132,6 +132,8 @@ The physics layers the query will detect (as a bitmask). By default, all collisi The list of object :ref:`RID`\ s that will be excluded from collisions. Use :ref:`CollisionObject3D.get_rid` to get the :ref:`RID` associated with a :ref:`CollisionObject3D`-derived node. +\ **Note:** The returned array is copied and any changes to it will not update the original property value. To update the value you need to modify the returned array, and then assign it to the property again. + .. rst-class:: classref-item-separator ---- diff --git a/classes/class_physicsshapequeryparameters2d.rst b/classes/class_physicsshapequeryparameters2d.rst index d374905b9..793282d97 100644 --- a/classes/class_physicsshapequeryparameters2d.rst +++ b/classes/class_physicsshapequeryparameters2d.rst @@ -122,6 +122,8 @@ The physics layers the query will detect (as a bitmask). By default, all collisi The list of object :ref:`RID`\ s that will be excluded from collisions. Use :ref:`CollisionObject2D.get_rid` to get the :ref:`RID` associated with a :ref:`CollisionObject2D`-derived node. +\ **Note:** The returned array is copied and any changes to it will not update the original property value. To update the value you need to modify the returned array, and then assign it to the property again. + .. rst-class:: classref-item-separator ---- diff --git a/classes/class_physicsshapequeryparameters3d.rst b/classes/class_physicsshapequeryparameters3d.rst index 67ae0a513..bc2b871df 100644 --- a/classes/class_physicsshapequeryparameters3d.rst +++ b/classes/class_physicsshapequeryparameters3d.rst @@ -122,6 +122,8 @@ The physics layers the query will detect (as a bitmask). By default, all collisi The list of object :ref:`RID`\ s that will be excluded from collisions. Use :ref:`CollisionObject3D.get_rid` to get the :ref:`RID` associated with a :ref:`CollisionObject3D`-derived node. +\ **Note:** The returned array is copied and any changes to it will not update the original property value. To update the value you need to modify the returned array, and then assign it to the property again. + .. rst-class:: classref-item-separator ---- diff --git a/classes/class_popupmenu.rst b/classes/class_popupmenu.rst index 07e5d0822..d58bc3a54 100644 --- a/classes/class_popupmenu.rst +++ b/classes/class_popupmenu.rst @@ -148,6 +148,8 @@ Methods +--------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | :ref:`bool` | :ref:`is_item_shortcut_disabled`\ (\ index\: :ref:`int`\ ) |const| | +--------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + | :ref:`bool` | :ref:`is_native_menu`\ (\ ) |const| | + +--------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | :ref:`bool` | :ref:`is_system_menu`\ (\ ) |const| | +--------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | |void| | :ref:`remove_item`\ (\ index\: :ref:`int`\ ) | @@ -445,6 +447,8 @@ The number of items currently in the list. If ``true``, :ref:`MenuBar` will use native menu when supported. +\ **Note:** If **PopupMenu** is linked to :ref:`StatusIndicator`, :ref:`MenuBar`, or another **PopupMenu** item it can use native menu regardless of this property, use :ref:`is_native_menu` to check it. + .. rst-class:: classref-item-separator ---- @@ -1076,6 +1080,18 @@ Returns ``true`` if the specified item's shortcut is disabled. ---- +.. _class_PopupMenu_method_is_native_menu: + +.. rst-class:: classref-method + +:ref:`bool` **is_native_menu**\ (\ ) |const| :ref:`🔗` + +Returns ``true`` if the system native menu is supported and currently used by this **PopupMenu**. + +.. rst-class:: classref-item-separator + +---- + .. _class_PopupMenu_method_is_system_menu: .. rst-class:: classref-method diff --git a/classes/class_projectsettings.rst b/classes/class_projectsettings.rst index 8ffc46646..9c12aa193 100644 --- a/classes/class_projectsettings.rst +++ b/classes/class_projectsettings.rst @@ -279,6 +279,8 @@ Properties +---------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+ | :ref:`int` | :ref:`debug/settings/profiler/max_functions` | ``16384`` | +---------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+ + | :ref:`int` | :ref:`debug/settings/profiler/max_timestamp_query_elements` | ``256`` | + +---------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+ | :ref:`bool` | :ref:`debug/settings/stdout/print_fps` | ``false`` | +---------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+ | :ref:`bool` | :ref:`debug/settings/stdout/print_gpu_profile` | ``false`` | @@ -3198,6 +3200,18 @@ Maximum number of functions per frame allowed when profiling. ---- +.. _class_ProjectSettings_property_debug/settings/profiler/max_timestamp_query_elements: + +.. rst-class:: classref-property + +:ref:`int` **debug/settings/profiler/max_timestamp_query_elements** = ``256`` :ref:`🔗` + +Maximum number of timestamp query elements allowed per frame for visual profiling. + +.. rst-class:: classref-item-separator + +---- + .. _class_ProjectSettings_property_debug/settings/stdout/print_fps: .. rst-class:: classref-property @@ -4220,9 +4234,9 @@ Defines how the base size is stretched to fit the resolution of the window or sc \ **"disabled"**: No stretching happens. One unit in the scene corresponds to one pixel on the screen. In this mode, :ref:`display/window/stretch/aspect` has no effect. Recommended for non-game applications. -\ **"canvas_items"**: The base size specified in width and height in the project settings is stretched to cover the whole screen (taking :ref:`display/window/stretch/aspect` into account). This means that everything is rendered directly at the target resolution. 3D is unaffected, while in 2D, there is no longer a 1:1 correspondence between sprite pixels and screen pixels, which may result in scaling artifacts. Recommended for most games that don't use a pixel art esthetic, although it is possible to use this stretch mode for pixel art games too (especially in 3D). +\ **"canvas_items"**: The base size specified in width and height in the project settings is stretched to cover the whole screen (taking :ref:`display/window/stretch/aspect` into account). This means that everything is rendered directly at the target resolution. 3D is unaffected, while in 2D, there is no longer a 1:1 correspondence between sprite pixels and screen pixels, which may result in scaling artifacts. Recommended for most games that don't use a pixel art aesthetic, although it is possible to use this stretch mode for pixel art games too (especially in 3D). -\ **"viewport"**: The size of the root :ref:`Viewport` is set precisely to the base size specified in the Project Settings' Display section. The scene is rendered to this viewport first. Finally, this viewport is scaled to fit the screen (taking :ref:`display/window/stretch/aspect` into account). Recommended for games that use a pixel art esthetic. +\ **"viewport"**: The size of the root :ref:`Viewport` is set precisely to the base size specified in the Project Settings' Display section. The scene is rendered to this viewport first. Finally, this viewport is scaled to fit the screen (taking :ref:`display/window/stretch/aspect` into account). Recommended for games that use a pixel art aesthetic. .. rst-class:: classref-item-separator @@ -4336,9 +4350,11 @@ Changing this value allows setting up a multi-project scenario where there are m :ref:`bool` **editor/export/convert_text_resources_to_binary** = ``true`` :ref:`🔗` -If ``true``, text resources are converted to a binary format on export. This decreases file sizes and speeds up loading slightly. +If ``true``, text resource (``tres``) and text scene (``tscn``) files are converted to their corresponding binary format on export. This decreases file sizes and speeds up loading slightly. -\ **Note:** If :ref:`editor/export/convert_text_resources_to_binary` is ``true``, :ref:`@GDScript.load` will not be able to return the converted files in an exported project. Some file paths within the exported PCK will also change, such as ``project.godot`` becoming ``project.binary``. If you rely on run-time loading of files present within the PCK, set :ref:`editor/export/convert_text_resources_to_binary` to ``false``. +\ **Note:** Because a resource's file extension may change in an exported project, it is heavily recommended to use :ref:`@GDScript.load` or :ref:`ResourceLoader` instead of :ref:`FileAccess` to load resources dynamically. + +\ **Note:** The project settings file (``project.godot``) will always be converted to binary on export, regardless of this setting. .. rst-class:: classref-item-separator diff --git a/classes/class_renderdataextension.rst b/classes/class_renderdataextension.rst index c90e048a6..b6981ea11 100644 --- a/classes/class_renderdataextension.rst +++ b/classes/class_renderdataextension.rst @@ -54,7 +54,7 @@ Method Descriptions :ref:`RID` **_get_camera_attributes**\ (\ ) |virtual| |const| :ref:`🔗` -Implement this in GDExtension to return the :ref:`RID` for the implementations camera attributes object. +Implement this in GDExtension to return the :ref:`RID` for the implementation's camera attributes object. .. rst-class:: classref-item-separator @@ -66,9 +66,7 @@ Implement this in GDExtension to return the :ref:`RID` for the implem :ref:`RID` **_get_environment**\ (\ ) |virtual| |const| :ref:`🔗` -.. container:: contribute - - There is currently no description for this method. Please help us by :ref:`contributing one `! +Implement this in GDExtension to return the :ref:`RID` of the implementation's environment object. .. rst-class:: classref-item-separator @@ -80,7 +78,7 @@ Implement this in GDExtension to return the :ref:`RID` for the implem :ref:`RenderSceneBuffers` **_get_render_scene_buffers**\ (\ ) |virtual| |const| :ref:`🔗` -Implement this in GDExtension to return the :ref:`RID` of the implementations environment object. +Implement this in GDExtension to return the implementation's :ref:`RenderSceneBuffers` object. .. rst-class:: classref-item-separator @@ -92,7 +90,7 @@ Implement this in GDExtension to return the :ref:`RID` of the impleme :ref:`RenderSceneData` **_get_render_scene_data**\ (\ ) |virtual| |const| :ref:`🔗` -Implement this in GDExtension to return the implementations :ref:`RenderSceneDataExtension` object. +Implement this in GDExtension to return the implementation's :ref:`RenderSceneDataExtension` object. .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)` .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)` diff --git a/classes/class_scripteditorbase.rst b/classes/class_scripteditorbase.rst index 5dcd5fc91..062c0e7e0 100644 --- a/classes/class_scripteditorbase.rst +++ b/classes/class_scripteditorbase.rst @@ -144,7 +144,7 @@ Emitted when the user contextual goto and the item is in the same script. .. rst-class:: classref-signal -**request_save_previous_state**\ (\ line\: :ref:`int`\ ) :ref:`🔗` +**request_save_previous_state**\ (\ state\: :ref:`Dictionary`\ ) :ref:`🔗` Emitted when the user changes current script or moves caret by 10 or more columns within the same script. diff --git a/classes/class_transform2d.rst b/classes/class_transform2d.rst index ccf25f0fb..476b1c5c0 100644 --- a/classes/class_transform2d.rst +++ b/classes/class_transform2d.rst @@ -17,10 +17,14 @@ A 2×3 matrix representing a 2D transformation. Description ----------- -A 2×3 matrix (2 rows, 3 columns) used for 2D linear transformations. It can represent transformations such as translation, rotation, and scaling. It consists of three :ref:`Vector2` values: :ref:`x`, :ref:`y`, and the :ref:`origin`. +The **Transform2D** built-in :ref:`Variant` type is a 2×3 `matrix `__ representing a transformation in 2D space. It contains three :ref:`Vector2` values: :ref:`x`, :ref:`y`, and :ref:`origin`. Together, they can represent translation, rotation, scale, and skew. + +The :ref:`x` and :ref:`y` axes form a 2×2 matrix, known as the transform's **basis**. The length of each axis (:ref:`Vector2.length`) influences the transform's scale, while the direction of all axes influence the rotation. Usually, both axes are perpendicular to one another. However, when you rotate one axis individually, the transform becomes skewed. Applying a skewed transform to a 2D sprite will make the sprite appear distorted. For a general introduction, see the :doc:`Matrices and transforms <../tutorials/math/matrices_and_transforms>` tutorial. +\ **Note:** Unlike :ref:`Transform3D`, there is no 2D equivalent to the :ref:`Basis` type. All mentions of "basis" refer to the :ref:`x` and :ref:`y` components of **Transform2D**. + .. note:: There are notable differences when using this API with C#. See :ref:`doc_c_sharp_differences` for more information. @@ -173,7 +177,24 @@ Constants **IDENTITY** = ``Transform2D(1, 0, 0, 1, 0, 0)`` :ref:`🔗` -The identity **Transform2D** with no translation, rotation or scaling applied. When applied to other data structures, :ref:`IDENTITY` performs no transformation. +The identity **Transform2D**. A transform with no translation, no rotation, and its scale being ``1``. When multiplied by another :ref:`Variant` such as :ref:`Rect2` or another **Transform2D**, no transformation occurs. This means that: + +- The :ref:`x` points right (:ref:`Vector2.RIGHT`); + +- The :ref:`y` points up (:ref:`Vector2.UP`). + +:: + + var transform = Transform2D.IDENTITY + print("| X | Y | Origin") + print("| %s | %s | %s" % [transform.x.x, transform.y.x, transform.origin.x]) + print("| %s | %s | %s" % [transform.x.y, transform.y.y, transform.origin.y]) + # Prints: + # | X | Y | Origin + # | 1 | 0 | 0 + # | 0 | 1 | 0 + +This is identical to creating :ref:`Transform2D` without any parameters. This constant can be used to make your code clearer, and for consistency with C#. .. _class_Transform2D_constant_FLIP_X: @@ -181,7 +202,9 @@ The identity **Transform2D** with no translation, rotation or scaling applied. W **FLIP_X** = ``Transform2D(-1, 0, 0, 1, 0, 0)`` :ref:`🔗` -The **Transform2D** that will flip something along the X axis. +When any transform is multiplied by :ref:`FLIP_X`, it negates all components of the :ref:`x` axis (the X column). + +When :ref:`FLIP_X` is multiplied by any basis, it negates the :ref:`Vector2.x` component of all axes (the X row). .. _class_Transform2D_constant_FLIP_Y: @@ -189,7 +212,9 @@ The **Transform2D** that will flip something along the X axis. **FLIP_Y** = ``Transform2D(1, 0, 0, -1, 0, 0)`` :ref:`🔗` -The **Transform2D** that will flip something along the Y axis. +When any transform is multiplied by :ref:`FLIP_Y`, it negates all components of the :ref:`y` axis (the Y column). + +When :ref:`FLIP_Y` is multiplied by any basis, it negates the :ref:`Vector2.y` component of all axes (the Y row). .. rst-class:: classref-section-separator @@ -206,7 +231,7 @@ Property Descriptions :ref:`Vector2` **origin** = ``Vector2(0, 0)`` :ref:`🔗` -The origin vector (column 2, the third column). Equivalent to array index ``2``. The origin vector represents translation. +The translation offset of this transform, and the column ``2`` of the matrix. In 2D space, this can be seen as the position. .. rst-class:: classref-item-separator @@ -218,7 +243,9 @@ The origin vector (column 2, the third column). Equivalent to array index ``2``. :ref:`Vector2` **x** = ``Vector2(1, 0)`` :ref:`🔗` -The basis matrix's X vector (column 0). Equivalent to array index ``0``. +The transform basis's X axis, and the column ``0`` of the matrix. Combined with :ref:`y`, this represents the transform's rotation, scale, and skew. + +On the identity transform, this vector points right (:ref:`Vector2.RIGHT`). .. rst-class:: classref-item-separator @@ -230,7 +257,9 @@ The basis matrix's X vector (column 0). Equivalent to array index ``0``. :ref:`Vector2` **y** = ``Vector2(0, 1)`` :ref:`🔗` -The basis matrix's Y vector (column 1). Equivalent to array index ``1``. +The transform basis's Y axis, and the column ``1`` of the matrix. Combined with :ref:`x`, this represents the transform's rotation, scale, and skew. + +On the identity transform, this vector points up (:ref:`Vector2.UP`). .. rst-class:: classref-section-separator @@ -247,7 +276,7 @@ Constructor Descriptions :ref:`Transform2D` **Transform2D**\ (\ ) :ref:`🔗` -Constructs a default-initialized **Transform2D** set to :ref:`IDENTITY`. +Constructs a **Transform2D** identical to :ref:`IDENTITY`. .. rst-class:: classref-item-separator @@ -267,7 +296,7 @@ Constructs a **Transform2D** as a copy of the given **Transform2D**. :ref:`Transform2D` **Transform2D**\ (\ rotation\: :ref:`float`, position\: :ref:`Vector2`\ ) -Constructs the transform from a given angle (in radians) and position. +Constructs a **Transform2D** from a given angle (in radians) and position. .. rst-class:: classref-item-separator @@ -277,7 +306,7 @@ Constructs the transform from a given angle (in radians) and position. :ref:`Transform2D` **Transform2D**\ (\ rotation\: :ref:`float`, scale\: :ref:`Vector2`, skew\: :ref:`float`, position\: :ref:`Vector2`\ ) -Constructs the transform from a given angle (in radians), scale, skew (in radians) and position. +Constructs a **Transform2D** from a given angle (in radians), scale, skew (in radians), and position. .. rst-class:: classref-item-separator @@ -287,7 +316,7 @@ Constructs the transform from a given angle (in radians), scale, skew (in radian :ref:`Transform2D` **Transform2D**\ (\ x_axis\: :ref:`Vector2`, y_axis\: :ref:`Vector2`, origin\: :ref:`Vector2`\ ) -Constructs the transform from 3 :ref:`Vector2` values representing :ref:`x`, :ref:`y`, and the :ref:`origin` (the three column vectors). +Constructs a **Transform2D** from 3 :ref:`Vector2` values representing :ref:`x`, :ref:`y`, and the :ref:`origin` (the three matrix columns). .. rst-class:: classref-section-separator @@ -304,7 +333,9 @@ Method Descriptions :ref:`Transform2D` **affine_inverse**\ (\ ) |const| :ref:`🔗` -Returns the inverse of the transform, under the assumption that the basis is invertible (must have non-zero determinant). +Returns the inverted version of this transform. Unlike :ref:`inverse`, this method works with almost any basis, including non-uniform ones, but is slower. See also :ref:`inverse`. + +\ **Note:** For this method to return correctly, the transform's basis needs to have a determinant that is not exactly ``0`` (see :ref:`determinant`). .. rst-class:: classref-item-separator @@ -316,9 +347,7 @@ Returns the inverse of the transform, under the assumption that the basis is inv :ref:`Vector2` **basis_xform**\ (\ v\: :ref:`Vector2`\ ) |const| :ref:`🔗` -Returns a vector transformed (multiplied) by the basis matrix. - -This method does not account for translation (the :ref:`origin` vector). +Returns a copy of the ``v`` vector, transformed (multiplied) by the transform basis's matrix. Unlike the multiplication operator (``*``), this method ignores the :ref:`origin`. .. rst-class:: classref-item-separator @@ -330,13 +359,9 @@ This method does not account for translation (the :ref:`origin` **basis_xform_inv**\ (\ v\: :ref:`Vector2`\ ) |const| :ref:`🔗` -Returns a vector transformed (multiplied) by the inverse basis matrix, under the assumption that the basis is orthonormal (i.e. rotation/reflection is fine, scaling/skew is not). +Returns a copy of the ``v`` vector, transformed (multiplied) by the inverse transform basis's matrix (see :ref:`inverse`). This method ignores the :ref:`origin`. -This method does not account for translation (the :ref:`origin` vector). - -\ ``transform.basis_xform_inv(vector)`` is equivalent to ``transform.inverse().basis_xform(vector)``. See :ref:`inverse`. - -For non-orthonormal transforms (e.g. with scaling) ``transform.affine_inverse().basis_xform(vector)`` can be used instead. See :ref:`affine_inverse`. +\ **Note:** This method assumes that this transform's basis is *orthonormal* (see :ref:`orthonormalized`). If the basis is not orthonormal, ``transform.affine_inverse().basis_xform(vector)`` should be used instead (see :ref:`affine_inverse`). .. rst-class:: classref-item-separator @@ -348,9 +373,13 @@ For non-orthonormal transforms (e.g. with scaling) ``transform.affine_inverse(). :ref:`float` **determinant**\ (\ ) |const| :ref:`🔗` -Returns the determinant of the basis matrix. If the basis is uniformly scaled, then its determinant equals the square of the scale factor. +Returns the `determinant `__ of this transform basis's matrix. For advanced math, this number can be used to determine a few attributes: -A negative determinant means the basis was flipped, so one part of the scale is negative. A zero determinant means the basis isn't invertible, and is usually considered invalid. +- If the determinant is exactly ``0``, the basis is not invertible (see :ref:`inverse`). + +- If the determinant is a negative number, the basis represents a negative scale. + +\ **Note:** If the basis's scale is the same for every axis, its determinant is always that scale by the power of 2. .. rst-class:: classref-item-separator @@ -362,7 +391,7 @@ A negative determinant means the basis was flipped, so one part of the scale is :ref:`Vector2` **get_origin**\ (\ ) |const| :ref:`🔗` -Returns the transform's origin (translation). +Returns this transform's translation. Equivalent to :ref:`origin`. .. rst-class:: classref-item-separator @@ -374,7 +403,7 @@ Returns the transform's origin (translation). :ref:`float` **get_rotation**\ (\ ) |const| :ref:`🔗` -Returns the transform's rotation (in radians). +Returns this transform's rotation (in radians). This is equivalent to :ref:`x`'s angle (see :ref:`Vector2.angle`). .. rst-class:: classref-item-separator @@ -386,7 +415,38 @@ Returns the transform's rotation (in radians). :ref:`Vector2` **get_scale**\ (\ ) |const| :ref:`🔗` -Returns the scale. +Returns the length of both :ref:`x` and :ref:`y`, as a :ref:`Vector2`. If this transform's basis is not skewed, this value is the scaling factor. It is not affected by rotation. + + +.. tabs:: + + .. code-tab:: gdscript + + var my_transform = Transform2D( + Vector2(2, 0), + Vector2(0, 4), + Vector2(0, 0) + ) + # Rotating the Transform2D in any way preserves its scale. + my_transform = my_transform.rotated(TAU / 2) + + print(my_transform.get_scale()) # Prints (2, 4). + + .. code-tab:: csharp + + var myTransform = new Transform2D( + Vector3(2.0f, 0.0f), + Vector3(0.0f, 4.0f), + Vector3(0.0f, 0.0f) + ); + // Rotating the Transform2D in any way preserves its scale. + myTransform = myTransform.Rotated(Mathf.Tau / 2.0f); + + GD.Print(myTransform.GetScale()); // Prints (2, 4, 8). + + + +\ **Note:** If the value returned by :ref:`determinant` is negative, the scale is also negative. .. rst-class:: classref-item-separator @@ -398,7 +458,7 @@ Returns the scale. :ref:`float` **get_skew**\ (\ ) |const| :ref:`🔗` -Returns the transform's skew (in radians). +Returns this transform's skew (in radians). .. rst-class:: classref-item-separator @@ -410,7 +470,9 @@ Returns the transform's skew (in radians). :ref:`Transform2D` **interpolate_with**\ (\ xform\: :ref:`Transform2D`, weight\: :ref:`float`\ ) |const| :ref:`🔗` -Returns a transform interpolated between this transform and another by a given ``weight`` (on the range of 0.0 to 1.0). +Returns the result of the linear interpolation between this transform and ``xform`` by the given ``weight``. + +The ``weight`` should be between ``0.0`` and ``1.0`` (inclusive). Values outside this range are allowed and can be used to perform *extrapolation* instead. .. rst-class:: classref-item-separator @@ -422,7 +484,9 @@ Returns a transform interpolated between this transform and another by a given ` :ref:`Transform2D` **inverse**\ (\ ) |const| :ref:`🔗` -Returns the inverse of the transform, under the assumption that the transformation basis is orthonormal (i.e. rotation/reflection is fine, scaling/skew is not). Use :ref:`affine_inverse` for non-orthonormal transforms (e.g. with scaling). +Returns the `inverted version of this transform `__. + +\ **Note:** For this method to return correctly, the transform's basis needs to be *orthonormal* (see :ref:`orthonormalized`). That means, the basis should only represent a rotation. If it does not, use :ref:`affine_inverse` instead. .. rst-class:: classref-item-separator @@ -434,7 +498,7 @@ Returns the inverse of the transform, under the assumption that the transformati :ref:`bool` **is_conformal**\ (\ ) |const| :ref:`🔗` -Returns ``true`` if the transform's basis is conformal, meaning it preserves angles and distance ratios, and may only be composed of rotation and uniform scale. Returns ``false`` if the transform's basis has non-uniform scale or shear/skew. This can be used to validate if the transform is non-distorted, which is important for physics and other use cases. +Returns ``true`` if this transform's basis is conformal. A conformal basis is both *orthogonal* (the axes are perpendicular to each other) and *uniform* (the axes share the same length). This method can be especially useful during physics calculations. .. rst-class:: classref-item-separator @@ -470,9 +534,7 @@ Returns ``true`` if this transform is finite, by calling :ref:`@GlobalScope.is_f :ref:`Transform2D` **looking_at**\ (\ target\: :ref:`Vector2` = Vector2(0, 0)\ ) |const| :ref:`🔗` -Returns a copy of the transform rotated such that the rotated X-axis points towards the ``target`` position. - -Operations take place in global space. +Returns a copy of the transform rotated such that the rotated X-axis points towards the ``target`` position, in global space. .. rst-class:: classref-item-separator @@ -484,7 +546,7 @@ Operations take place in global space. :ref:`Transform2D` **orthonormalized**\ (\ ) |const| :ref:`🔗` -Returns the transform with the basis orthogonal (90 degrees), and normalized axis vectors (scale of 1 or -1). +Returns a copy of this transform with its basis orthonormalized. An orthonormal basis is both *orthogonal* (the axes are perpendicular to each other) and *normalized* (the axes have a length of ``1``), which also means it can only represent rotation. .. rst-class:: classref-item-separator @@ -597,7 +659,7 @@ Operator Descriptions :ref:`bool` **operator !=**\ (\ right\: :ref:`Transform2D`\ ) :ref:`🔗` -Returns ``true`` if the transforms are not equal. +Returns ``true`` if the components of both transforms are not equal. \ **Note:** Due to floating-point precision errors, consider using :ref:`is_equal_approx` instead, which is more reliable. @@ -611,7 +673,9 @@ Returns ``true`` if the transforms are not equal. :ref:`PackedVector2Array` **operator ***\ (\ right\: :ref:`PackedVector2Array`\ ) :ref:`🔗` -Transforms (multiplies) each element of the :ref:`Vector2` array by the given **Transform2D** matrix. +Transforms (multiplies) every :ref:`Vector2` element of the given :ref:`PackedVector2Array` by this transformation matrix. + +On larger arrays, this operation is much faster than transforming each :ref:`Vector2` individually. .. rst-class:: classref-item-separator @@ -623,7 +687,7 @@ Transforms (multiplies) each element of the :ref:`Vector2` array :ref:`Rect2` **operator ***\ (\ right\: :ref:`Rect2`\ ) :ref:`🔗` -Transforms (multiplies) the :ref:`Rect2` by the given **Transform2D** matrix. +Transforms (multiplies) the :ref:`Rect2` by this transformation matrix. .. rst-class:: classref-item-separator @@ -635,7 +699,17 @@ Transforms (multiplies) the :ref:`Rect2` by the given **Transform2D :ref:`Transform2D` **operator ***\ (\ right\: :ref:`Transform2D`\ ) :ref:`🔗` -Composes these two transformation matrices by multiplying them together. This has the effect of transforming the second transform (the child) by the first transform (the parent). +Transforms (multiplies) this transform by the ``right`` transform. + +This is the operation performed between parent and child :ref:`CanvasItem` nodes. + +\ **Note:** If you need to only modify one attribute of this transform, consider using one of the following methods, instead: + +- For translation, see :ref:`translated` or :ref:`translated_local`. + +- For rotation, see :ref:`rotated` or :ref:`rotated_local`. + +- For scale, see :ref:`scaled` or :ref:`scaled_local`. .. rst-class:: classref-item-separator @@ -647,7 +721,7 @@ Composes these two transformation matrices by multiplying them together. This ha :ref:`Vector2` **operator ***\ (\ right\: :ref:`Vector2`\ ) :ref:`🔗` -Transforms (multiplies) the :ref:`Vector2` by the given **Transform2D** matrix. +Transforms (multiplies) the :ref:`Vector2` by this transformation matrix. .. rst-class:: classref-item-separator @@ -659,7 +733,7 @@ Transforms (multiplies) the :ref:`Vector2` by the given **Transfo :ref:`Transform2D` **operator ***\ (\ right\: :ref:`float`\ ) :ref:`🔗` -This operator multiplies all components of the **Transform2D**, including the :ref:`origin` vector, which scales it uniformly. +Multiplies all components of the **Transform2D** by the given :ref:`float`, including the :ref:`origin`. This affects the transform's scale uniformly. .. rst-class:: classref-item-separator @@ -671,7 +745,7 @@ This operator multiplies all components of the **Transform2D**, including the :r :ref:`Transform2D` **operator ***\ (\ right\: :ref:`int`\ ) :ref:`🔗` -This operator multiplies all components of the **Transform2D**, including the :ref:`origin` vector, which scales it uniformly. +Multiplies all components of the **Transform2D** by the given :ref:`int`, including the :ref:`origin`. This affects the transform's scale uniformly. .. rst-class:: classref-item-separator @@ -683,7 +757,7 @@ This operator multiplies all components of the **Transform2D**, including the :r :ref:`Transform2D` **operator /**\ (\ right\: :ref:`float`\ ) :ref:`🔗` -This operator divides all components of the **Transform2D**, including the :ref:`origin` vector, which inversely scales it uniformly. +Divides all components of the **Transform2D** by the given :ref:`float`, including the :ref:`origin`. This affects the transform's scale uniformly. .. rst-class:: classref-item-separator @@ -695,7 +769,7 @@ This operator divides all components of the **Transform2D**, including the :ref: :ref:`Transform2D` **operator /**\ (\ right\: :ref:`int`\ ) :ref:`🔗` -This operator divides all components of the **Transform2D**, including the :ref:`origin` vector, which inversely scales it uniformly. +Divides all components of the **Transform2D** by the given :ref:`int`, including the :ref:`origin`. This affects the transform's scale uniformly. .. rst-class:: classref-item-separator @@ -707,7 +781,7 @@ This operator divides all components of the **Transform2D**, including the :ref: :ref:`bool` **operator ==**\ (\ right\: :ref:`Transform2D`\ ) :ref:`🔗` -Returns ``true`` if the transforms are exactly equal. +Returns ``true`` if the components of both transforms are exactly equal. \ **Note:** Due to floating-point precision errors, consider using :ref:`is_equal_approx` instead, which is more reliable. @@ -721,7 +795,7 @@ Returns ``true`` if the transforms are exactly equal. :ref:`Vector2` **operator []**\ (\ index\: :ref:`int`\ ) :ref:`🔗` -Access transform components using their index. ``t[0]`` is equivalent to ``t.x``, ``t[1]`` is equivalent to ``t.y``, and ``t[2]`` is equivalent to ``t.origin``. +Accesses each axis (column) of this transform by their index. Index ``0`` is the same as :ref:`x`, index ``1`` is the same as :ref:`y`, and index ``2`` is the same as :ref:`origin`. .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)` .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)` diff --git a/classes/class_xrinterface.rst b/classes/class_xrinterface.rst index ce3e8e907..6b0dcdc5a 100644 --- a/classes/class_xrinterface.rst +++ b/classes/class_xrinterface.rst @@ -704,6 +704,14 @@ Triggers a haptic pulse on a device associated with this interface. \ ``tracker_name`` is optional and can be used to direct the pulse to a specific device provided that device is bound to this haptic. +\ ``frequency`` is the frequency of the pulse, set to ``0.0`` to have the system use a default frequency. + +\ ``amplitude`` is the amplitude of the pulse between ``0.0`` and ``1.0``. + +\ ``duration_sec`` is the duration of the pulse in seconds. + +\ ``delay_sec`` is a delay in seconds before the pulse is given. + .. rst-class:: classref-item-separator ---- diff --git a/classes/class_xrnode3d.rst b/classes/class_xrnode3d.rst index 675e6db7b..e6a064261 100644 --- a/classes/class_xrnode3d.rst +++ b/classes/class_xrnode3d.rst @@ -196,6 +196,14 @@ Triggers a haptic pulse on a device associated with this interface. \ ``action_name`` is the name of the action for this pulse. +\ ``frequency`` is the frequency of the pulse, set to ``0.0`` to have the system use a default frequency. + +\ ``amplitude`` is the amplitude of the pulse between ``0.0`` and ``1.0``. + +\ ``duration_sec`` is the duration of the pulse in seconds. + +\ ``delay_sec`` is a delay in seconds before the pulse is given. + .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)` .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)` .. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`