using_transforms.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. .. _doc_using_transforms:
  2. Using 3D transforms
  3. ~~~~~~~~~~~~~~~~~~~
  4. Introduction
  5. ------------
  6. If you have never made 3D games before, working with rotations in three dimensions can be confusing at first.
  7. Coming from 2D, the natural way of thinking is along the lines of *"Oh, it's just like rotating in 2D, except now rotations happen in X, Y and Z"*.
  8. At first, this seems easy. For simple games, this way of thinking may even be enough. Unfortunately, it's often incorrect.
  9. Angles in three dimensions are most commonly referred to as "Euler Angles".
  10. .. image:: img/transforms_euler.png
  11. Euler angles were introduced by mathematician Leonhard Euler in the early 1700s.
  12. .. image:: img/transforms_euler_himself.png
  13. This way of representing 3D rotations was groundbreaking at the time, but it has several shortcomings when used in game development (which is to be expected from a guy with a funny
  14. hat).
  15. The idea of this document is to explain why, as well as outlining best practices for dealing with transforms when programming 3D games.
  16. Problems of Euler angles
  17. ------------------------
  18. While it may seem intuitive that each axis has a rotation, the truth is that it's just not practical.
  19. Axis order
  20. ==========
  21. The main reason for this is that there isn't a *unique* way to construct an orientation from the angles. There isn't a standard mathematical function that
  22. takes all the angles together and produces an actual 3D rotation. The only way an orientation can be produced from angles is to rotate the object angle
  23. by angle, in an *arbitrary order*.
  24. This could be done by first rotating in *X*, then *Y* and then in *Z*. Alternatively, you could first rotate in *Y*, then in *Z* and finally in *X*. Anything works,
  25. but depending on the order, the final orientation of the object will *not necessarily be the same*. Indeed, this means that there are several ways to construct an orientation
  26. from 3 different angles, depending on *the order of the rotations*.
  27. Following is a visualization of rotation axes (in X, Y, Z order) in a gimbal (from Wikipedia). As you can see, the orientation of each axis depends on the rotation of the previous one:
  28. .. image:: img/transforms_gimbal.gif
  29. You may be wondering how this affects you. Let's look at a practical example:
  30. Imagine you are working on a first-person controller (e.g. an FPS game). Moving the mouse left and right controls your view angle parallel to the ground, while moving it up and down moves the player's view up and down.
  31. In this case to achieve the desired effect, rotation must be applied first in the *Y* axis ("up" in this case, since Godot uses a "Y-Up" orientation), followed by rotation in the *X* axis.
  32. .. image:: img/transforms_rotate1.gif
  33. If we were to apply rotation in the *X* axis first, and then in *Y*, the effect would be undesired:
  34. .. image:: img/transforms_rotate2.gif
  35. Depending on the type of game or effect desired, the order in which you want axis rotations to be applied may differ. Therefore, applying rotations in X, Y, and Z is not enough: you also need a *rotation order*.
  36. Interpolation
  37. =============
  38. Another problem with using Euler angles is interpolation. Imagine you want to transition between two different camera or enemy positions (including rotations). One logical way to approach this is to interpolate the angles from one position to the next. One would expect it to look like this:
  39. .. image:: img/transforms_interpolate1.gif
  40. But this does not always have the expected effect when using angles:
  41. .. image:: img/transforms_interpolate2.gif
  42. The camera actually rotated the opposite direction!
  43. There are a few reasons this may happen:
  44. * Rotations don't map linearly to orientation, so interpolating them does not always result in the shortest path (i.e., to go from ``270`` to ``0`` degrees is not the same as going from ``270`` to ``360``, even though the angles are equivalent).
  45. * Gimbal lock is at play (first and last rotated axis align, so a degree of freedom is lost). See `Wikipedia's page on Gimbal Lock <https://en.wikipedia.org/wiki/Gimbal_lock>`_ for a detailed explanation of this problem.
  46. Say no to Euler angles
  47. ======================
  48. The result of all this is that you should **not use** the ``rotation`` property of :ref:`class_Spatial` nodes in Godot for games. It's there to be used mainly in the editor, for coherence with the 2D engine, and for simple rotations (generally just one axis, or even two in limited cases). As much as you may be tempted, don't use it.
  49. Instead, there is a better way to solve your rotation problems.
  50. Introducing transforms
  51. ----------------------
  52. Godot uses the :ref:`class_Transform` datatype for orientations. Each :ref:`class_Spatial` node contains a ``transform`` property which is relative to the parent's transform, if the parent is a Spatial-derived type.
  53. It is also possible to access the world coordinate transform via the ``global_transform`` property.
  54. A transform has a :ref:`class_Basis` (transform.basis sub-property), which consists of three :ref:`class_Vector3` vectors. These are accessed via the ``transform.basis`` property and can be accessed directly by ``transform.basis.x``, ``transform.basis.y``, and ``transform.basis.z``. Each vector points in the direction its axis has been rotated, so they effectively describe the node's total rotation. The scale (as long as it's uniform) can also be inferred from the length of the axes. A *basis* can also be interpreted as a 3x3 matrix and used as ``transform.basis[x][y]``.
  55. A default basis (unmodified) is akin to:
  56. .. tabs::
  57. .. code-tab:: gdscript GDScript
  58. var basis = Basis()
  59. # Contains the following default values:
  60. basis.x = Vector3(1, 0, 0) # Vector pointing along the X axis
  61. basis.y = Vector3(0, 1, 0) # Vector pointing along the Y axis
  62. basis.z = Vector3(0, 0, 1) # Vector pointing along the Z axis
  63. .. code-tab:: csharp
  64. // Due to technical limitations on structs in C# the default
  65. // constructor will contain zero values for all fields.
  66. var defaultBasis = new Basis();
  67. GD.Print(defaultBasis); // prints: ((0, 0, 0), (0, 0, 0), (0, 0, 0))
  68. // Instead we can use the Identity property.
  69. var identityBasis = Basis.Identity;
  70. GD.Print(identityBasis.x); // prints: (1, 0, 0)
  71. GD.Print(identityBasis.y); // prints: (0, 1, 0)
  72. GD.Print(identityBasis.z); // prints: (0, 0, 1)
  73. // The Identity basis is equivalent to:
  74. var basis = new Basis(Vector3.Right, Vector3.Up, Vector3.Back);
  75. GD.Print(basis); // prints: ((1, 0, 0), (0, 1, 0), (0, 0, 1))
  76. This is also an analog of a 3x3 identity matrix.
  77. Following the OpenGL convention, ``X`` is the *Right* axis, ``Y`` is the *Up* axis and ``Z`` is the *Forward* axis.
  78. Together with the *basis*, a transform also has an *origin*. This is a *Vector3* specifying how far away from the actual origin ``(0, 0, 0)`` this transform is. Combining the *basis* with the *origin*, a *transform* efficiently represents a unique translation, rotation, and scale in space.
  79. .. image:: img/transforms_camera.png
  80. One way to visualize a transform is to look at an object's 3D gizmo while in "local space" mode.
  81. .. image:: img/transforms_local_space.png
  82. The gizmo's arrows show the ``X``, ``Y``, and ``Z`` axes (in red, green, and blue respectively) of the basis, while the gizmo's center is at the object's origin.
  83. .. image:: img/transforms_gizmo.png
  84. For more information on the mathematics of vectors and transforms, please read the :ref:`doc_vector_math` tutorials.
  85. Manipulating transforms
  86. =======================
  87. Of course, transforms are not as straightforward to manipulate as angles and have problems of their own.
  88. It is possible to rotate a transform, either by multiplying its basis by another (this is called accumulation), or by using the rotation methods.
  89. .. tabs::
  90. .. code-tab:: gdscript GDScript
  91. var axis = Vector3(1, 0, 0) # Or Vector3.RIGHT
  92. var rotation_amount = 0.1
  93. # Rotate the transform around the X axis by 0.1 radians.
  94. transform.basis = Basis(axis, rotation_amount) * transform.basis
  95. # shortened
  96. transform.basis = transform.basis.rotated(axis, rotation_amount)
  97. .. code-tab:: csharp
  98. Vector3 axis = new Vector3(1, 0, 0); // Or Vector3.Right
  99. float rotationAmount = 0.1f;
  100. // Rotate the transform around the X axis by 0.1 radians.
  101. transform.basis = new Basis(axis, rotationAmount) * transform.basis;
  102. // shortened
  103. transform.basis = transform.basis.Rotated(axis, rotationAmount);
  104. A method in Spatial simplifies this:
  105. .. tabs::
  106. .. code-tab:: gdscript GDScript
  107. # Rotate the transform around the X axis by 0.1 radians.
  108. rotate(Vector3(1, 0, 0), 0.1)
  109. # shortened
  110. rotate_x(0.1)
  111. .. code-tab:: csharp
  112. // Rotate the transform around the X axis by 0.1 radians.
  113. Rotate(new Vector3(1, 0, 0), 0.1f);
  114. // shortened
  115. RotateX(0.1f);
  116. This rotates the node relative to the parent node.
  117. To rotate relative to object space (the node's own transform), use the following:
  118. .. tabs::
  119. .. code-tab:: gdscript GDScript
  120. # Rotate around the object's local X axis by 0.1 radians.
  121. rotate_object_local(Vector3(1, 0, 0), 0.1)
  122. .. code-tab:: csharp
  123. // Rotate around the object's local X axis by 0.1 radians.
  124. RotateObjectLocal(new Vector3(1, 0, 0), 0.1f);
  125. Precision errors
  126. ================
  127. Doing successive operations on transforms will result in a loss of precision due to floating-point error. This means the scale of each axis may no longer be exactly ``1.0``, and they may not be exactly ``90`` degrees from each other.
  128. If a transform is rotated every frame, it will eventually start deforming over time. This is unavoidable.
  129. There are two different ways to handle this. The first is to *orthonormalize* the transform after some time (maybe once per frame if you modify it every frame):
  130. .. tabs::
  131. .. code-tab:: gdscript GDScript
  132. transform = transform.orthonormalized()
  133. .. code-tab:: csharp
  134. transform = transform.Orthonormalized();
  135. This will make all axes have ``1.0`` length again and be ``90`` degrees from each other. However, any scale applied to the transform will be lost.
  136. It is recommended you not scale nodes that are going to be manipulated; scale their children nodes instead (such as MeshInstance). If you absolutely must scale the node, then re-apply it at the end:
  137. .. tabs::
  138. .. code-tab:: gdscript GDScript
  139. transform = transform.orthonormalized()
  140. transform = transform.scaled(scale)
  141. .. code-tab:: csharp
  142. transform = transform.Orthonormalized();
  143. transform = transform.Scaled(scale);
  144. Obtaining information
  145. =====================
  146. You might be thinking at this point: **"Ok, but how do I get angles from a transform?"**. The answer again is: you don't. You must do your best to stop thinking in angles.
  147. Imagine you need to shoot a bullet in the direction your player is facing. Just use the forward axis (commonly ``Z`` or ``-Z``).
  148. .. tabs::
  149. .. code-tab:: gdscript GDScript
  150. bullet.transform = transform
  151. bullet.speed = transform.basis.z * BULLET_SPEED
  152. .. code-tab:: csharp
  153. bullet.Transform = transform;
  154. bullet.LinearVelocity = transform.basis.z * BulletSpeed;
  155. Is the enemy looking at the player? Use the dot product for this (see the :ref:`doc_vector_math` tutorial for an explanation of the dot product):
  156. .. tabs::
  157. .. code-tab:: gdscript GDScript
  158. # Get the direction vector from player to enemy
  159. var direction = enemy.transform.origin - player.transform.origin
  160. if direction.dot(enemy.transform.basis.z) > 0:
  161. enemy.im_watching_you(player)
  162. .. code-tab:: csharp
  163. // Get the direction vector from player to enemy
  164. Vector3 direction = enemy.Transform.origin - player.Transform.origin;
  165. if (direction.Dot(enemy.Transform.basis.z) > 0)
  166. {
  167. enemy.ImWatchingYou(player);
  168. }
  169. Strafe left:
  170. .. tabs::
  171. .. code-tab:: gdscript GDScript
  172. # Remember that +X is right
  173. if Input.is_action_pressed("strafe_left"):
  174. translate_object_local(-transform.basis.x)
  175. .. code-tab:: csharp
  176. // Remember that +X is right
  177. if (Input.IsActionPressed("strafe_left"))
  178. {
  179. TranslateObjectLocal(-Transform.basis.x);
  180. }
  181. Jump:
  182. .. tabs::
  183. .. code-tab:: gdscript GDScript
  184. # Keep in mind Y is up-axis
  185. if Input.is_action_just_pressed("jump"):
  186. velocity.y = JUMP_SPEED
  187. velocity = move_and_slide(velocity)
  188. .. code-tab:: csharp
  189. // Keep in mind Y is up-axis
  190. if (Input.IsActionJustPressed("jump"))
  191. velocity.y = JumpSpeed;
  192. velocity = MoveAndSlide(velocity);
  193. All common behaviors and logic can be done with just vectors.
  194. Setting information
  195. ===================
  196. There are, of course, cases where you want to set information to a transform. Imagine a first person controller or orbiting camera. Those are definitely done using angles, because you *do want* the transforms to happen in a specific order.
  197. For such cases, keep the angles and rotations *outside* the transform and set them every frame. Don't try to retrieve and re-use them because the transform is not meant to be used this way.
  198. Example of looking around, FPS style:
  199. .. tabs::
  200. .. code-tab:: gdscript GDScript
  201. # accumulators
  202. var rot_x = 0
  203. var rot_y = 0
  204. func _input(event):
  205. if event is InputEventMouseMotion and event.button_mask & 1:
  206. # modify accumulated mouse rotation
  207. rot_x += event.relative.x * LOOKAROUND_SPEED
  208. rot_y += event.relative.y * LOOKAROUND_SPEED
  209. transform.basis = Basis() # reset rotation
  210. rotate_object_local(Vector3(0, 1, 0), rot_x) # first rotate in Y
  211. rotate_object_local(Vector3(1, 0, 0), rot_y) # then rotate in X
  212. .. code-tab:: csharp
  213. // accumulators
  214. private float _rotationX = 0f;
  215. private float _rotationY = 0f;
  216. public override void _Input(InputEvent @event)
  217. {
  218. if (@event is InputEventMouseMotion mouseMotion)
  219. {
  220. // modify accumulated mouse rotation
  221. _rotationX += mouseMotion.Relative.x * LookAroundSpeed;
  222. _rotationY += mouseMotion.Relative.y * LookAroundSpeed;
  223. // reset rotation
  224. Transform transform = Transform;
  225. transform.basis = Basis.Identity;
  226. Transform = transform;
  227. RotateObjectLocal(Vector3.Up, _rotationX); // first rotate about Y
  228. RotateObjectLocal(Vector3.Right, _rotationY); // then rotate about X
  229. }
  230. }
  231. As you can see, in such cases it's even simpler to keep the rotation outside, then use the transform as the *final* orientation.
  232. Interpolating with quaternions
  233. ==============================
  234. Interpolating between two transforms can efficiently be done with quaternions. More information about how quaternions work can be found in other places around the Internet. For practical use, it's enough to understand that pretty much their main use is doing a closest path interpolation. As in, if you have two rotations, a quaternion will smoothly allow interpolation between them using the closest axis.
  235. Converting a rotation to quaternion is straightforward.
  236. .. tabs::
  237. .. code-tab:: gdscript GDScript
  238. # Convert basis to quaternion, keep in mind scale is lost
  239. var a = Quat(transform.basis)
  240. var b = Quat(transform2.basis)
  241. # Interpolate using spherical-linear interpolation (SLERP).
  242. var c = a.slerp(b,0.5) # find halfway point between a and b
  243. # Apply back
  244. transform.basis = Basis(c)
  245. .. code-tab:: csharp
  246. // Convert basis to quaternion, keep in mind scale is lost
  247. var a = transform.basis.Quat();
  248. var b = transform2.basis.Quat();
  249. // Interpolate using spherical-linear interpolation (SLERP).
  250. var c = a.Slerp(b, 0.5f); // find halfway point between a and b
  251. // Apply back
  252. transform.basis = new Basis(c);
  253. The :ref:`class_Quat` type reference has more information on the datatype (it
  254. can also do transform accumulation, transform points, etc., though this is used
  255. less often). If you interpolate or apply operations to quaternions many times,
  256. keep in mind they need to be eventually normalized. Otherwise, they will also
  257. suffer from numerical precision errors.
  258. Quaternions are useful when doing camera/path/etc. interpolations, as the result will always be correct and smooth.
  259. Transforms are your friend
  260. --------------------------
  261. For most beginners, getting used to working with transforms can take some time. However, once you get used to them, you will appreciate their simplicity and power.
  262. Don't hesitate to ask for help on this topic in any of Godot's `online communities <https://godotengine.org/community>`_ and, once you become confident enough, please help others!