vector_math.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. .. _doc_vector_math:
  2. Vector math
  3. ===========
  4. Introduction
  5. ~~~~~~~~~~~~
  6. This tutorial is a short and practical introduction to linear algebra as it
  7. applies to game development. Linear algebra is the study of vectors and their
  8. uses. Vectors have many applications in both 2D and 3D development and Godot
  9. uses them extensively. Developing a good understanding of vector math is
  10. essential to becoming a strong game developer.
  11. .. note:: This tutorial is **not** a formal textbook on linear algebra. We will
  12. only be looking at how it is applied to game development. For a
  13. broader look at the mathematics, see
  14. https://www.khanacademy.org/math/linear-algebra
  15. Coordinate systems (2D)
  16. ~~~~~~~~~~~~~~~~~~~~~~~
  17. In 2D space, coordinates are defined using a horizontal axis (``x``) and a
  18. vertical axis (``y``). A particular position in 2D space is written as a pair of
  19. values such as ``(4, 3)``.
  20. .. image:: img/vector_axis1.png
  21. .. note:: If you're new to computer graphics, it might seem odd that the
  22. positive ``y`` axis points **downwards** instead of upwards, as you
  23. probably learned in math class. However, this is common in most
  24. computer graphics applications.
  25. Any position in the 2D plane can be identified by a pair of numbers in this way.
  26. However, we can also think of the position ``(4, 3)`` as an **offset** from the
  27. ``(0, 0)`` point, or **origin**. Draw an arrow pointing from the origin to the
  28. point:
  29. .. image:: img/vector_xy1.png
  30. This is a **vector**. A vector represents a lot of useful information. As well
  31. as telling us that the point is at ``(4, 3)``, we can also think of it as an
  32. angle ``θ`` (theta) and a length (or magnitude) ``m``. In this case, the arrow
  33. is a **position vector** - it denotes a position in space, relative to the
  34. origin.
  35. A very important point to consider about vectors is that they only represent
  36. **relative** direction and magnitude. There is no concept of a vector's
  37. position. The following two vectors are identical:
  38. .. image:: img/vector_xy2.png
  39. Both vectors represent a point 4 units to the right and 3 units below some
  40. starting point. It does not matter where on the plane you draw the vector, it
  41. always represents a relative direction and magnitude.
  42. Vector operations
  43. ~~~~~~~~~~~~~~~~~
  44. You can use either method (x and y coordinates or angle and magnitude) to refer
  45. to a vector, but for convenience, programmers typically use the coordinate
  46. notation. For example, in Godot, the origin is the top-left corner of the
  47. screen, so to place a 2D node named ``Node2D`` 400 pixels to the right and 300
  48. pixels down, use the following code:
  49. .. tabs::
  50. .. code-tab:: gdscript GDScript
  51. $Node2D.position = Vector2(400, 300)
  52. .. code-tab:: csharp
  53. var node2D = GetNode<Node2D>("Node2D");
  54. node2D.Position = new Vector2(400, 300);
  55. Godot supports both :ref:`Vector2 <class_Vector2>` and :ref:`Vector3
  56. <class_Vector3>` for 2D and 3D usage, respectively. The same mathematical rules
  57. discussed in this article apply to both types, and wherever we link to
  58. ``Vector2`` methods in the class reference, you can also check out their
  59. ``Vector3`` counterparts.
  60. Member access
  61. -------------
  62. The individual components of the vector can be accessed directly by name.
  63. .. tabs::
  64. .. code-tab:: gdscript GDScript
  65. # Create a vector with coordinates (2, 5).
  66. var a = Vector2(2, 5)
  67. # Create a vector and assign x and y manually.
  68. var b = Vector2()
  69. b.x = 3
  70. b.y = 1
  71. .. code-tab:: csharp
  72. // Create a vector with coordinates (2, 5).
  73. var a = new Vector2(2, 5);
  74. // Create a vector and assign x and y manually.
  75. var b = new Vector2();
  76. b.X = 3;
  77. b.Y = 1;
  78. Adding vectors
  79. --------------
  80. When adding or subtracting two vectors, the corresponding components are added:
  81. .. tabs::
  82. .. code-tab:: gdscript GDScript
  83. var c = a + b # (2, 5) + (3, 1) = (5, 6)
  84. .. code-tab:: csharp
  85. var c = a + b; // (2, 5) + (3, 1) = (5, 6)
  86. We can also see this visually by adding the second vector at the end of
  87. the first:
  88. .. image:: img/vector_add1.png
  89. Note that adding ``a + b`` gives the same result as ``b + a``.
  90. Scalar multiplication
  91. ---------------------
  92. .. note:: Vectors represent both direction and magnitude. A value representing
  93. only magnitude is called a **scalar**. Scalars use the
  94. :ref:`class_float` type in Godot.
  95. A vector can be multiplied by a **scalar**:
  96. .. tabs::
  97. .. code-tab:: gdscript GDScript
  98. var c = a * 2 # (2, 5) * 2 = (4, 10)
  99. var d = b / 3 # (3, 6) / 3 = (1, 2)
  100. .. code-tab:: csharp
  101. var c = a * 2; // (2, 5) * 2 = (4, 10)
  102. var d = b / 3; // (3, 6) / 3 = (1, 2)
  103. .. image:: img/vector_mult1.png
  104. .. note:: Multiplying a vector by a scalar does not change its direction, only
  105. its magnitude. This is how you **scale** a vector.
  106. Practical applications
  107. ~~~~~~~~~~~~~~~~~~~~~~
  108. Let's look at two common uses for vector addition and subtraction.
  109. Movement
  110. --------
  111. A vector can represent **any** quantity with a magnitude and direction. Typical
  112. examples are: position, velocity, acceleration, and force. In this image, the
  113. spaceship at step 1 has a position vector of ``(1, 3)`` and a velocity vector of
  114. ``(2, 1)``. The velocity vector represents how far the ship moves each step. We
  115. can find the position for step 2 by adding the velocity to the current position.
  116. .. image:: img/vector_movement1.png
  117. .. tip:: Velocity measures the **change** in position per unit of time. The new
  118. position is found by adding the velocity multiplied by the elapsed time
  119. (here assumed to be one unit, e.g. 1 s) to the previous position.
  120. In a typical 2D game scenario, you would have a velocity in pixels per
  121. second, and multiply it by the ``delta`` parameter (time elapsed since
  122. the previous frame) from the :ref:`_process() <class_Node_method__process>`
  123. or :ref:`_physics_process() <class_Node_method__physics_process>`
  124. callbacks.
  125. Pointing toward a target
  126. ------------------------
  127. In this scenario, you have a tank that wishes to point its turret at a robot.
  128. Subtracting the tank's position from the robot's position gives the vector
  129. pointing from the tank to the robot.
  130. .. image:: img/vector_subtract2.webp
  131. .. tip:: To find a vector pointing from ``A`` to ``B``, use ``B - A``.
  132. Unit vectors
  133. ~~~~~~~~~~~~
  134. A vector with **magnitude** of ``1`` is called a **unit vector**. They are also
  135. sometimes referred to as **direction vectors** or **normals**. Unit vectors are
  136. helpful when you need to keep track of a direction.
  137. Normalization
  138. -------------
  139. **Normalizing** a vector means reducing its length to ``1`` while preserving its
  140. direction. This is done by dividing each of its components by its magnitude.
  141. Because this is such a common operation, Godot provides a dedicated
  142. :ref:`normalized() <class_Vector2_method_normalized>` method for this:
  143. .. tabs::
  144. .. code-tab:: gdscript GDScript
  145. a = a.normalized()
  146. .. code-tab:: csharp
  147. a = a.Normalized();
  148. .. warning:: Because normalization involves dividing by the vector's length, you
  149. cannot normalize a vector of length ``0``. Attempting to do so
  150. would normally result in an error. In GDScript though, trying to
  151. call the ``normalized()`` method on a vector of length 0 leaves the
  152. value untouched and avoids the error for you.
  153. Reflection
  154. ----------
  155. A common use of unit vectors is to indicate **normals**. Normal vectors are unit
  156. vectors aligned perpendicularly to a surface, defining its direction. They are
  157. commonly used for lighting, collisions, and other operations involving surfaces.
  158. For example, imagine we have a moving ball that we want to bounce off a wall or
  159. other object:
  160. .. image:: img/vector_reflect1.png
  161. The surface normal has a value of ``(0, -1)`` because this is a horizontal
  162. surface. When the ball collides, we take its remaining motion (the amount left
  163. over when it hits the surface) and reflect it using the normal. In Godot, there
  164. is a :ref:`bounce() <class_Vector2_method_bounce>` method to handle this.
  165. Here is a code example of the above diagram using a :ref:`CharacterBody2D
  166. <class_CharacterBody2D>`:
  167. .. tabs::
  168. .. code-tab:: gdscript GDScript
  169. var collision: KinematicCollision2D = move_and_collide(velocity * delta)
  170. if collision:
  171. var reflect = collision.get_remainder().bounce(collision.get_normal())
  172. velocity = velocity.bounce(collision.get_normal())
  173. move_and_collide(reflect)
  174. .. code-tab:: csharp
  175. KinematicCollision2D collision = MoveAndCollide(_velocity * (float)delta);
  176. if (collision != null)
  177. {
  178. var reflect = collision.GetRemainder().Bounce(collision.GetNormal());
  179. _velocity = _velocity.Bounce(collision.GetNormal());
  180. MoveAndCollide(reflect);
  181. }
  182. Dot product
  183. ~~~~~~~~~~~
  184. The **dot product** is one of the most important concepts in vector math, but is
  185. often misunderstood. Dot product is an operation on two vectors that returns a
  186. **scalar**. Unlike a vector, which contains both magnitude and direction, a
  187. scalar value has only magnitude.
  188. The formula for dot product takes two common forms:
  189. .. image:: img/vector_dot1.png
  190. and
  191. .. image:: img/vector_dot2.png
  192. The mathematical notation *||A||* represents the magnitude of vector ``A``, and
  193. *A*\ :sub:`x` means the ``x`` component of vector ``A``.
  194. However, in most cases it is easiest to use the built-in :ref:`dot()
  195. <class_Vector2_method_dot>` method. Note that the order of the two vectors does not matter:
  196. .. tabs::
  197. .. code-tab:: gdscript GDScript
  198. var c = a.dot(b)
  199. var d = b.dot(a) # These are equivalent.
  200. .. code-tab:: csharp
  201. float c = a.Dot(b);
  202. float d = b.Dot(a); // These are equivalent.
  203. The dot product is most useful when used with unit vectors, making the first
  204. formula reduce to just ``cos(θ)``. This means we can use the dot product to tell
  205. us something about the angle between two vectors:
  206. .. image:: img/vector_dot3.png
  207. When using unit vectors, the result will always be between ``-1`` (180°) and
  208. ``1`` (0°).
  209. Facing
  210. ------
  211. We can use this fact to detect whether an object is facing toward another
  212. object. In the diagram below, the player ``P`` is trying to avoid the zombies
  213. ``A`` and ``B``. Assuming a zombie's field of view is **180°**, can they see the
  214. player?
  215. .. image:: img/vector_facing2.png
  216. The green arrows ``fA`` and ``fB`` are **unit vectors** representing the
  217. zombie's facing direction and the blue semicircle represents its field of view.
  218. For zombie ``A``, we find the direction vector ``AP`` pointing to the player
  219. using ``P - A`` and normalize it, however, Godot has a helper method to do this
  220. called :ref:`direction_to() <class_Vector2_method_direction_to>`. If the angle
  221. between this vector and the facing vector is less than 90°, then the zombie can
  222. see the player.
  223. In code it would look like this:
  224. .. tabs::
  225. .. code-tab:: gdscript GDScript
  226. var AP = A.direction_to(P)
  227. if AP.dot(fA) > 0:
  228. print("A sees P!")
  229. .. code-tab:: csharp
  230. var AP = A.DirectionTo(P);
  231. if (AP.Dot(fA) > 0)
  232. {
  233. GD.Print("A sees P!");
  234. }
  235. Cross product
  236. ~~~~~~~~~~~~~
  237. Like the dot product, the **cross product** is an operation on two vectors.
  238. However, the result of the cross product is a vector with a direction that is
  239. perpendicular to both. Its magnitude depends on their relative angle. If two
  240. vectors are parallel, the result of their cross product will be a null vector.
  241. .. image:: img/vector_cross1.png
  242. .. image:: img/vector_cross2.png
  243. The cross product is calculated like this:
  244. .. tabs::
  245. .. code-tab:: gdscript GDScript
  246. var c = Vector3()
  247. c.x = (a.y * b.z) - (a.z * b.y)
  248. c.y = (a.z * b.x) - (a.x * b.z)
  249. c.z = (a.x * b.y) - (a.y * b.x)
  250. .. code-tab:: csharp
  251. var c = new Vector3();
  252. c.X = (a.Y * b.Z) - (a.Z * b.Y);
  253. c.Y = (a.Z * b.X) - (a.X * b.Z);
  254. c.Z = (a.X * b.Y) - (a.Y * b.X);
  255. With Godot, you can use the built-in :ref:`Vector3.cross() <class_Vector3_method_cross>`
  256. method:
  257. .. tabs::
  258. .. code-tab:: gdscript GDScript
  259. var c = a.cross(b)
  260. .. code-tab:: csharp
  261. var c = a.Cross(b);
  262. The cross product is not mathematically defined in 2D. The :ref:`Vector2.cross()
  263. <class_Vector2_method_cross>` method is a commonly used analog of the 3D cross
  264. product for 2D vectors.
  265. .. note:: In the cross product, order matters. ``a.cross(b)`` does not give the
  266. same result as ``b.cross(a)``. The resulting vectors point in
  267. **opposite** directions.
  268. Calculating normals
  269. -------------------
  270. One common use of cross products is to find the surface normal of a plane or
  271. surface in 3D space. If we have the triangle ``ABC`` we can use vector
  272. subtraction to find two edges ``AB`` and ``AC``. Using the cross product,
  273. ``AB × AC`` produces a vector perpendicular to both: the surface normal.
  274. Here is a function to calculate a triangle's normal:
  275. .. tabs::
  276. .. code-tab:: gdscript GDScript
  277. func get_triangle_normal(a, b, c):
  278. # Find the surface normal given 3 vertices.
  279. var side1 = b - a
  280. var side2 = c - a
  281. var normal = side1.cross(side2)
  282. return normal
  283. .. code-tab:: csharp
  284. Vector3 GetTriangleNormal(Vector3 a, Vector3 b, Vector3 c)
  285. {
  286. // Find the surface normal given 3 vertices.
  287. var side1 = b - a;
  288. var side2 = c - a;
  289. var normal = side1.Cross(side2);
  290. return normal;
  291. }
  292. Pointing to a target
  293. --------------------
  294. In the dot product section above, we saw how it could be used to find the angle
  295. between two vectors. However, in 3D, this is not enough information. We also
  296. need to know what axis to rotate around. We can find that by calculating the
  297. cross product of the current facing direction and the target direction. The
  298. resulting perpendicular vector is the axis of rotation.
  299. More information
  300. ~~~~~~~~~~~~~~~~
  301. For more information on using vector math in Godot, see the following articles:
  302. - :ref:`doc_vectors_advanced`
  303. - :ref:`doc_matrices_and_transforms`