using_transforms.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. .. _doc_using_transforms:
  2. Using transforms for 3D games in Godot
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Introduction
  5. ------------
  6. If you have never made 3D games before, the way to approach rotations with three dimensions can be very confusing at first.
  7. Coming from 2D, the natural way of thinking is along the lines of *"Oh, it's just like roating in 2D, except now rotations happen in X, Y and Z"*.
  8. At first this seems easy and, for simple games, this way of thinking may even be enough. Unfortunately, It's just very limiting and most often incorrect.
  9. Angles in three dimensions are most commonly refered 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 a 3D rotation has several shortcomings when used in game development (which is to be expected from a guy with a funny hat), and
  14. the idea of this document is to explain why, as well as outlining best practices for dealing with transforms when programming 3D games.
  15. Problems of Euler Angles
  16. ------------------------
  17. While it may seem very intuitive that each axis has a rotation, the truth is that it's just not practical.
  18. Axis Order
  19. ==========
  20. 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
  21. takes all the angles togehter and produces an actual 3D rotation. The only way an orientation can be produced from angles is to rotate the object angle
  22. by angle, in an *arbitrary order*.
  23. 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 really works,
  24. but depending on the order, the final orientation of the object will *not necesarily be the same*. Indeed, this means that there are several ways to construct an orientation
  25. from 3 different angles, depending on *the order the rotations happen*.
  26. Following is a visualization of rotation axes (in X,Y,Z order) in a gimbal (from Wikipedia). As it can be appreciated, the orientation of each axis depends on the rotation of the previous one:
  27. .. image:: img/transforms_gimbal.gif
  28. You may be wondering how this might affect you, though. Let's go to a practical example, then.
  29. Imagine you are working on a first person controller (FPS game). Moving the mouse left and right (2D screen X axis) controls your view angle based on the ground, while moving it up and down
  30. makes the player head look actually up and down.
  31. In this case, to achieve the desired effect, rotation should be applied first in *Y* axis (Up in our case, as Godot uses Y-Up), and then in *X* axis.
  32. .. image:: img/transforms_rotate1.gif
  33. If we were to simply apply rotation in *X* axis first, 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. Just accessing rotations as X,Y and Z is not enough, you need a *rotation order*.
  36. Interpolation
  37. =============
  38. Another problem of using euler angles is interpolation. Imagine you want to transition between two different camera or enemy positions (including rotations). The logical way one may
  39. approach is is to just interpolate the angles from one position to to the next. One would expect it to look like this:
  40. .. image:: img/transforms_interpolate1.gif
  41. But this does not always have the expected effect when using angles:
  42. .. image:: img/transforms_interpolate2.gif
  43. The camera actually rotated the opposite direction!
  44. There are reasons for this to have happened:
  45. * Rotations dont linearly map to orientation, so interpolating them does not always result in the closest path (ie, to go from 270 to 0 degrees is no the same as going from 270 to 360, even though angles are equivalent).
  46. * Gimbal lock is at play (first and last rotated axis align, so a degree of freedom is lost).
  47. Say no to Euler Angles
  48. ======================
  49. This means, pretty much, just **don't use** the *rotation* property of :ref:`class_Spatial` nodes in Godot for games. It's there to be used mainly fromt the editor, coherence with the 2D engine and for very simple rotations (generally just 1 axis, 2 in limited cases). As much as it tempts you, don't use it.
  50. There is always a better way around Euler Angles for your specific problem waiting to be found by you.
  51. Introducing Transforms
  52. ----------------------
  53. Godot uses the :ref:`class_Transform` datatype for orientations. Each :ref:`class_Spatial` node contains one of those transforms (via *transform* property), which is relative to the parent transform (in case the parent is of Spatial or derived type too).
  54. It is also possible to access the world coordinate transform (via *global_transform* property).
  55. A transform has a :ref:`class_Basis` (transform.basis sub-property), which consists of 3 :ref:`class_Vector3` vectors (transform.basis.x to transform.basis.z). Each points to the direction where each actual axis is rotated to, so they effectively contain a rotation. The scale (as long as it's uniform) can be also be inferred from the length of the axes. A *Basis* can also be interpreted as a 3x3 matrix (used as transform.basis[x][y]).
  56. A default basis (unmodified) is akin to:
  57. .. code-block:: python
  58. var basis = Basis()
  59. # Has these default values built-in (Below is redundant, but just to make it clear)
  60. basis.x = Vector3(1, 0, 0) # Vector pointing to X axis
  61. basis.y = Vector3(0, 1, 0) # Vector pointing to Y axis
  62. basis.z = Vector3(0, 0, 1) # Vector pointing to Z axis
  63. This is also analog to an 3x3 identity matrix.
  64. In Godot (following OpenGL convention), X is the *Right* axis, Y is the *Up* axis and Z is the *Forward* axis.
  65. 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 in xyz) this transform is. Together with the *basis*, a *Transform* efficiently represents a unique translation, rotation and scale in space.
  66. A simple way to visualize a transform is to just look at an object transform gizmo (in local mode). It will show the X, Y and Z axes (as red, green and blue respectively) of the basis as the arrows, while the origin is just the center of the gizmo (where arrows emerge) in space.
  67. .. image:: img/transforms_gizmo.png
  68. For more information on the mathematics of vectors and transforms, please read the :ref:`vector_math` tutorials.
  69. Manipulating Transforms
  70. =======================
  71. Of course, transforms are not nearly as straightforward to manipulate as angles and have problems of their own.
  72. It is possible to rotate a transform, by either multiplying it's basis by another (this is called accumulation), or just using the rotation methods.
  73. .. code-block:: python
  74. # Rotate the transform in X axis
  75. transform.basis = Basis( Vector3(1,0,0), PI ) * transform.basis
  76. # Simplified
  77. transform.basis = transform.basis.rotated( Vector3(1,0,0), PI )
  78. A method in Spatial simplifies this:
  79. .. code-block:: python
  80. # Rotate the transform in X axis
  81. rotate( Vector3(1,0,0), PI )
  82. # or, just shortened
  83. rotate_x( PI )
  84. This will rotate the node relative to the parent node space.
  85. To rotate relative to object space (node's own transform) the following must be done.
  86. .. code-block:: python
  87. # Rotate locally, notice multiplication order is inverted
  88. transform = transform * Basis( Vector3(1,0,0), PI )
  89. # or, shortened
  90. rotate_object_local( Vector3(1,0,0), PI )
  91. Precision Errors
  92. ================
  93. Doing successive operations on transforms will result in a precision degradation due to floating point error. This means scale of each axis may no longer be exactly 1.0, and not exactly 90 degrees from each other.
  94. If a transform is rotated every frame, it will eventually start deforming slightly long term. This is unavoidable.
  95. There are however, two different ways to handle this. The first is to orthonormalize the transform after a while (maybe once per frame if you modify it every frame):
  96. .. code-block:: python
  97. transform = transform.orthonormalized()
  98. This will make all axes have 1.0 length again and be 90 degrees from each other. If the transform had scale, it will be lost, though.
  99. It is recommended you don't scale nodes that are going to be manipulated, scale their children nodes instead (like MeshInstance). If you absolutely must have scale, then re-apply it in the end:
  100. .. code-block:: python
  101. transform = transform.orthonormalized()
  102. transform = transform.scaled( scale )
  103. Obtaining Information
  104. =====================
  105. You might be thinking at this point: **"Ok, but how do I get angles from a transform?"**. Answer is again, you don't. You must do your best to stop thinking in angles.
  106. Imagine you need to shoot a bullet in the direction your player is looking towards to. Just use the forward axis (commonly Z or -Z for this).
  107. .. code-block:: python
  108. bullet.transform = transform
  109. bullet.speed = transform.basis.z * BULLET_SPEED
  110. So, is the enemy looking at my player? you can use dot product for this (dot product is explained in the vector math tutorial linked before):
  111. .. code-block:: python
  112. if (enemy.transform.origin - player.transform.origin). dot( enemy.transform.basis.z ) > 0 ):
  113. enemy.im_watching_you(player)
  114. Let's strafe left!
  115. .. code-block:: python
  116. # Remember that X is Right
  117. if (Input.is_key_pressed("strafe_left")):
  118. translate_object_local( -transform.basis.x )
  119. Time to jump..
  120. .. code-block:: python
  121. # Keep in mind Y is up-axis
  122. if (Input.is_key_just_pressed("jump")):
  123. velocity.y = JUMP_SPEED
  124. velocity = move_and_slide( velocity )
  125. All common behaviors and logic can be done with just vectors.
  126. Setting Information
  127. ===================
  128. 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*
  129. the transforms to happen in a specific order.
  130. For such cases, just keep the angles and rotations *outside* the transform and set them every frame. Don't try retrieve them and re-use them because the transform is not meant to be used this way.
  131. Example of looking around, FPS style:
  132. .. code-block:: python
  133. # accumulators
  134. var rot_x = 0
  135. var rot_y = 0
  136. func _input(ev):
  137. if (ev is InputEventMouseMotion and ev.button_mask & 1):
  138. # modify accumulated mouse rotation
  139. rot_x += ev.relative.x * LOOKAROUND_SPEED
  140. rot_y += ev.relative.y * LOOKAROUND_SPEED
  141. transform.basis = Basis() # reset rotation
  142. rotate_object_local( Vector3(0,1,0), rot_x ) # first rotate in Y
  143. rotate_object_local( Vector3(1,0,0), rot_y ) # then rotate in X
  144. As you can see, in such cases it's even simpler to keep the rotation outside, then use the transform as the *final* orientation.
  145. Transforms are your friend
  146. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  147. Once you get used to transforms, you will appreciate their simplicity and power. Of course, for most starting with 3D games, getting used to them can take a while and it can be a bit tricky.
  148. Don't hesitate to ask for help in this topic in many of our online communities and, once you become confident enough, please help others!