vectors_advanced.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. .. _doc_vectors_advanced:
  2. Advanced vector math
  3. ====================
  4. Planes
  5. ~~~~~~
  6. The dot product has another interesting property with unit vectors.
  7. Imagine that perpendicular to that vector (and through the origin)
  8. passes a plane. Planes divide the entire space into positive
  9. (over the plane) and negative (under the plane), and (contrary to
  10. popular belief) you can also use their math in 2D:
  11. .. image:: img/tutovec10.png
  12. Unit vectors that are perpendicular to a surface (so, they describe the
  13. orientation of the surface) are called **unit normal vectors**. Though,
  14. usually they are just abbreviated as *normals*. Normals appear in
  15. planes, 3D geometry (to determine where each face or vertex is siding),
  16. etc. A **normal** *is* a **unit vector**, but it's called *normal*
  17. because of its usage. (Just like we call (0,0) the Origin!).
  18. The plane passes by the origin and the
  19. surface of it is perpendicular to the unit vector (or *normal*). The
  20. side towards the vector points to is the positive half-space, while the
  21. other side is the negative half-space. In 3D this is exactly the same,
  22. except that the plane is an infinite surface (imagine an infinite, flat
  23. sheet of paper that you can orient and is pinned to the origin) instead
  24. of a line.
  25. Distance to plane
  26. -----------------
  27. Now that it's clear what a plane is, let's go back to the dot product.
  28. The dot product between a **unit vector** and any **point in space**
  29. (yes, this time we do dot product between vector and position), returns
  30. the **distance from the point to the plane**:
  31. .. tabs::
  32. .. code-tab:: gdscript GDScript
  33. var distance = normal.dot(point)
  34. .. code-tab:: csharp
  35. var distance = normal.Dot(point);
  36. But not just the absolute distance, if the point is in the negative half
  37. space the distance will be negative, too:
  38. .. image:: img/tutovec11.png
  39. This allows us to tell which side of the plane a point is.
  40. Away from the origin
  41. --------------------
  42. I know what you are thinking! So far this is nice, but *real* planes are
  43. everywhere in space, not only passing through the origin. You want real
  44. *plane* action and you want it *now*.
  45. Remember that planes not only split space in two, but they also have
  46. *polarity*. This means that it is possible to have perfectly overlapping
  47. planes, but their negative and positive half-spaces are swapped.
  48. With this in mind, let's describe a full plane as a **normal** *N* and a
  49. **distance from the origin** scalar *D*. Thus, our plane is represented
  50. by N and D. For example:
  51. .. image:: img/tutovec12.png
  52. For 3D math, Godot provides a :ref:`Plane <class_Plane>`
  53. built-in type that handles this.
  54. Basically, N and D can represent any plane in space, be it for 2D or 3D
  55. (depending on the amount of dimensions of N) and the math is the same
  56. for both. It's the same as before, but D is the distance from the origin
  57. to the plane, travelling in N direction. As an example, imagine you want
  58. to reach a point in the plane, you will just do:
  59. .. tabs::
  60. .. code-tab:: gdscript GDScript
  61. var point_in_plane = N*D
  62. .. code-tab:: csharp
  63. var pointInPlane = N * D;
  64. This will stretch (resize) the normal vector and make it touch the
  65. plane. This math might seem confusing, but it's actually much simpler
  66. than it seems. If we want to tell, again, the distance from the point to
  67. the plane, we do the same but adjusting for distance:
  68. .. tabs::
  69. .. code-tab:: gdscript GDScript
  70. var distance = N.dot(point) - D
  71. .. code-tab:: csharp
  72. var distance = N.Dot(point) - D;
  73. The same thing, using a built-in function:
  74. .. tabs::
  75. .. code-tab:: gdscript GDScript
  76. var distance = plane.distance_to(point)
  77. .. code-tab:: csharp
  78. var distance = plane.DistanceTo(point);
  79. This will, again, return either a positive or negative distance.
  80. Flipping the polarity of the plane can be done by negating both
  81. N and D. This will result in a plane in the same position, but with
  82. inverted negative and positive half spaces:
  83. .. tabs::
  84. .. code-tab:: gdscript GDScript
  85. N = -N
  86. D = -D
  87. .. code-tab:: csharp
  88. N = -N;
  89. D = -D;
  90. Godot also implements this operator in :ref:`Plane <class_Plane>`.
  91. So, using the format below will work as expected:
  92. .. tabs::
  93. .. code-tab:: gdscript GDScript
  94. var inverted_plane = -plane
  95. .. code-tab:: csharp
  96. var invertedPlane = -plane;
  97. So, remember, the plane's main practical use is that we can
  98. calculate the distance to it. So, when is it useful to calculate the
  99. distance from a point to a plane? Let's see some examples.
  100. Constructing a plane in 2D
  101. --------------------------
  102. Planes clearly don't come out of nowhere, so they must be built.
  103. Constructing them in 2D is easy, this can be done from either a normal
  104. (unit vector) and a point, or from two points in space.
  105. In the case of a normal and a point, most of the work is done, as the
  106. normal is already computed, so calculate D from the dot product of
  107. the normal and the point.
  108. .. tabs::
  109. .. code-tab:: gdscript GDScript
  110. var N = normal
  111. var D = normal.dot(point)
  112. .. code-tab:: csharp
  113. var N = normal;
  114. var D = normal.Dot(point);
  115. For two points in space, there are actually two planes that pass through
  116. them, sharing the same space but with normal pointing to the opposite
  117. directions. To compute the normal from the two points, the direction
  118. vector must be obtained first, and then it needs to be rotated 90°
  119. degrees to either side:
  120. .. tabs::
  121. .. code-tab:: gdscript GDScript
  122. # Calculate vector from `a` to `b`.
  123. var dvec = (point_b - point_a).normalized()
  124. # Rotate 90 degrees.
  125. var normal = Vector2(dvec.y, -dvec.x)
  126. # Alternatively (depending the desired side of the normal):
  127. # var normal = Vector2(-dvec.y, dvec.x)
  128. .. code-tab:: csharp
  129. // Calculate vector from `a` to `b`.
  130. var dvec = (pointB - pointA).Normalized();
  131. // Rotate 90 degrees.
  132. var normal = new Vector2(dvec.y, -dvec.x);
  133. // Alternatively (depending the desired side of the normal):
  134. // var normal = new Vector2(-dvec.y, dvec.x);
  135. The rest is the same as the previous example. Either point_a or
  136. point_b will work, as they are in the same plane:
  137. .. tabs::
  138. .. code-tab:: gdscript GDScript
  139. var N = normal
  140. var D = normal.dot(point_a)
  141. # this works the same
  142. # var D = normal.dot(point_b)
  143. .. code-tab:: csharp
  144. var N = normal;
  145. var D = normal.Dot(pointA);
  146. // this works the same
  147. // var D = normal.Dot(pointB);
  148. Doing the same in 3D is a little more complex and is explained
  149. further down.
  150. Some examples of planes
  151. -----------------------
  152. Here is an example of what planes are useful for. Imagine you have
  153. a `convex <https://www.mathsisfun.com/definitions/convex.html>`__
  154. polygon. For example, a rectangle, a trapezoid, a triangle, or just any
  155. polygon where no faces bend inwards.
  156. For every segment of the polygon, we compute the plane that passes by
  157. that segment. Once we have the list of planes, we can do neat things,
  158. for example checking if a point is inside the polygon.
  159. We go through all planes, if we can find a plane where the distance to
  160. the point is positive, then the point is outside the polygon. If we
  161. can't, then the point is inside.
  162. .. image:: img/tutovec13.png
  163. Code should be something like this:
  164. .. tabs::
  165. .. code-tab:: gdscript GDScript
  166. var inside = true
  167. for p in planes:
  168. # check if distance to plane is positive
  169. if (p.distance_to(point) > 0):
  170. inside = false
  171. break # with one that fails, it's enough
  172. .. code-tab:: csharp
  173. var inside = true;
  174. foreach (var p in planes)
  175. {
  176. // check if distance to plane is positive
  177. if (p.DistanceTo(point) > 0)
  178. {
  179. inside = false;
  180. break; // with one that fails, it's enough
  181. }
  182. }
  183. Pretty cool, huh? But this gets much better! With a little more effort,
  184. similar logic will let us know when two convex polygons are overlapping
  185. too. This is called the Separating Axis Theorem (or SAT) and most
  186. physics engines use this to detect collision.
  187. With a point, just checking if a plane
  188. returns a positive distance is enough to tell if the point is outside.
  189. With another polygon, we must find a plane where *all* *the* *other*
  190. *polygon* *points* return a positive distance to it. This check is
  191. performed with the planes of A against the points of B, and then with
  192. the planes of B against the points of A:
  193. .. image:: img/tutovec14.png
  194. Code should be something like this:
  195. .. tabs::
  196. .. code-tab:: gdscript GDScript
  197. var overlapping = true
  198. for p in planes_of_A:
  199. var all_out = true
  200. for v in points_of_B:
  201. if (p.distance_to(v) < 0):
  202. all_out = false
  203. break
  204. if (all_out):
  205. # a separating plane was found
  206. # do not continue testing
  207. overlapping = false
  208. break
  209. if (overlapping):
  210. # only do this check if no separating plane
  211. # was found in planes of A
  212. for p in planes_of_B:
  213. var all_out = true
  214. for v in points_of_A:
  215. if (p.distance_to(v) < 0):
  216. all_out = false
  217. break
  218. if (all_out):
  219. overlapping = false
  220. break
  221. if (overlapping):
  222. print("Polygons Collided!")
  223. .. code-tab:: csharp
  224. var overlapping = true;
  225. foreach (Plane plane in planesOfA)
  226. {
  227. var allOut = true;
  228. foreach (Vector3 point in pointsOfB)
  229. {
  230. if (plane.DistanceTo(point) < 0)
  231. {
  232. allOut = false;
  233. break;
  234. }
  235. }
  236. if (allOut)
  237. {
  238. // a separating plane was found
  239. // do not continue testing
  240. overlapping = false;
  241. break;
  242. }
  243. }
  244. if (overlapping)
  245. {
  246. // only do this check if no separating plane
  247. // was found in planes of A
  248. foreach (Plane plane in planesOfB)
  249. {
  250. var allOut = true;
  251. foreach (Vector3 point in pointsOfA)
  252. {
  253. if (plane.DistanceTo(point) < 0)
  254. {
  255. allOut = false;
  256. break;
  257. }
  258. }
  259. if (allOut)
  260. {
  261. overlapping = false;
  262. break;
  263. }
  264. }
  265. }
  266. if (overlapping)
  267. {
  268. GD.Print("Polygons Collided!");
  269. }
  270. As you can see, planes are quite useful, and this is the tip of the
  271. iceberg. You might be wondering what happens with non convex polygons.
  272. This is usually just handled by splitting the concave polygon into
  273. smaller convex polygons, or using a technique such as BSP (which is not
  274. used much nowadays).
  275. Collision detection in 3D
  276. ~~~~~~~~~~~~~~~~~~~~~~~~~
  277. This is another bonus bit, a reward for being patient and keeping up
  278. with this long tutorial. Here is another piece of wisdom. This might
  279. not be something with a direct use case (Godot already does collision
  280. detection pretty well) but it's used by almost all physics engines and collision
  281. detection libraries :)
  282. Remember that converting a convex shape in 2D to an array of 2D planes
  283. was useful for collision detection? You could detect if a point was
  284. inside any convex shape, or if two 2D convex shapes were overlapping.
  285. Well, this works in 3D too, if two 3D polyhedral shapes are colliding,
  286. you won't be able to find a separating plane. If a separating plane is
  287. found, then the shapes are definitely not colliding.
  288. To refresh a bit a separating plane means that all vertices of polygon A
  289. are in one side of the plane, and all vertices of polygon B are in the
  290. other side. This plane is always one of the face-planes of either
  291. polygon A or polygon B.
  292. In 3D though, there is a problem to this approach, because it is
  293. possible that, in some cases a separating plane can't be found. This is
  294. an example of such situation:
  295. .. image:: img/tutovec22.png
  296. To avoid it, some extra planes need to be tested as separators, these
  297. planes are the cross product between the edges of polygon A and the
  298. edges of polygon B
  299. .. image:: img/tutovec23.png
  300. So the final algorithm is something like:
  301. .. tabs::
  302. .. code-tab:: gdscript GDScript
  303. var overlapping = true
  304. for p in planes_of_A:
  305. var all_out = true
  306. for v in points_of_B:
  307. if (p.distance_to(v) < 0):
  308. all_out = false
  309. break
  310. if (all_out):
  311. # a separating plane was found
  312. # do not continue testing
  313. overlapping = false
  314. break
  315. if (overlapping):
  316. # only do this check if no separating plane
  317. # was found in planes of A
  318. for p in planes_of_B:
  319. var all_out = true
  320. for v in points_of_A:
  321. if (p.distance_to(v) < 0):
  322. all_out = false
  323. break
  324. if (all_out):
  325. overlapping = false
  326. break
  327. if (overlapping):
  328. for ea in edges_of_A:
  329. for eb in edges_of_B:
  330. var n = ea.cross(eb)
  331. if (n.length() == 0):
  332. continue
  333. var max_A = -1e20 # tiny number
  334. var min_A = 1e20 # huge number
  335. # we are using the dot product directly
  336. # so we can map a maximum and minimum range
  337. # for each polygon, then check if they
  338. # overlap.
  339. for v in points_of_A:
  340. var d = n.dot(v)
  341. max_A = max(max_A, d)
  342. min_A = min(min_A, d)
  343. var max_B = -1e20 # tiny number
  344. var min_B = 1e20 # huge number
  345. for v in points_of_B:
  346. var d = n.dot(v)
  347. max_B = max(max_B, d)
  348. min_B = min(min_B, d)
  349. if (min_A > max_B or min_B > max_A):
  350. # not overlapping!
  351. overlapping = false
  352. break
  353. if (not overlapping):
  354. break
  355. if (overlapping):
  356. print("Polygons collided!")
  357. .. code-tab:: csharp
  358. var overlapping = true;
  359. foreach (Plane plane in planesOfA)
  360. {
  361. var allOut = true;
  362. foreach (Vector3 point in pointsOfB)
  363. {
  364. if (plane.DistanceTo(point) < 0)
  365. {
  366. allOut = false;
  367. break;
  368. }
  369. }
  370. if (allOut)
  371. {
  372. // a separating plane was found
  373. // do not continue testing
  374. overlapping = false;
  375. break;
  376. }
  377. }
  378. if (overlapping)
  379. {
  380. // only do this check if no separating plane
  381. // was found in planes of A
  382. foreach (Plane plane in planesOfB)
  383. {
  384. var allOut = true;
  385. foreach (Vector3 point in pointsOfA)
  386. {
  387. if (plane.DistanceTo(point) < 0)
  388. {
  389. allOut = false;
  390. break;
  391. }
  392. }
  393. if (allOut)
  394. {
  395. overlapping = false;
  396. break;
  397. }
  398. }
  399. }
  400. if (overlapping)
  401. {
  402. foreach (Vector3 edgeA in edgesOfA)
  403. {
  404. foreach (Vector3 edgeB in edgesOfB)
  405. {
  406. var normal = edgeA.Cross(edgeB);
  407. if (normal.Length() == 0)
  408. {
  409. continue;
  410. }
  411. var maxA = float.MinValue; // tiny number
  412. var minA = float.MaxValue; // huge number
  413. // we are using the dot product directly
  414. // so we can map a maximum and minimum range
  415. // for each polygon, then check if they
  416. // overlap.
  417. foreach (Vector3 point in pointsOfA)
  418. {
  419. var distance = normal.Dot(point);
  420. maxA = Mathf.Max(maxA, distance);
  421. minA = Mathf.Min(minA, distance);
  422. }
  423. var maxB = float.MinValue; // tiny number
  424. var minB = float.MaxValue; // huge number
  425. foreach (Vector3 point in pointsOfB)
  426. {
  427. var distance = normal.Dot(point);
  428. maxB = Mathf.Max(maxB, distance);
  429. minB = Mathf.Min(minB, distance);
  430. }
  431. if (minA > maxB || minB > maxA)
  432. {
  433. // not overlapping!
  434. overlapping = false;
  435. break;
  436. }
  437. }
  438. if (!overlapping)
  439. {
  440. break;
  441. }
  442. }
  443. }
  444. if (overlapping)
  445. {
  446. GD.Print("Polygons Collided!");
  447. }
  448. More information
  449. ~~~~~~~~~~~~~~~~
  450. For more information on using vector math in Godot, see the following article:
  451. - :ref:`doc_matrices_and_transforms`
  452. If you would like additional explanation, you should check out
  453. 3Blue1Brown's excellent video series "Essence of Linear Algebra":
  454. https://www.youtube.com/watch?v=fNk_zzaMoSs&list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab