vector_math.rst 13 KB

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