vectors_advanced.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. It's as simple as it looks. 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. Of course, Godot also implements this operator in :ref:`Plane <class_Plane>`,
  91. so doing:
  92. .. tabs::
  93. .. code-tab:: gdscript GDScript
  94. var inverted_plane = -plane
  95. .. code-tab:: csharp
  96. var invertedPlane = -plane;
  97. Will work as expected.
  98. So, remember, a plane is just that and its main practical use is
  99. calculating the distance to it. So, why is it useful to calculate the
  100. distance from a point to a plane? It's extremely useful! Let's see some
  101. simple examples..
  102. Constructing a plane in 2D
  103. --------------------------
  104. Planes clearly don't come out of nowhere, so they must be built.
  105. Constructing them in 2D is easy, this can be done from either a normal
  106. (unit vector) and a point, or from two points in space.
  107. In the case of a normal and a point, most of the work is done, as the
  108. normal is already computed, so just calculate D from the dot product of
  109. the normal and the point.
  110. .. tabs::
  111. .. code-tab:: gdscript GDScript
  112. var N = normal
  113. var D = normal.dot(point)
  114. .. code-tab:: csharp
  115. var N = normal;
  116. var D = normal.Dot(point);
  117. For two points in space, there are actually two planes that pass through
  118. them, sharing the same space but with normal pointing to the opposite
  119. directions. To compute the normal from the two points, the direction
  120. vector must be obtained first, and then it needs to be rotated 90°
  121. degrees to either side:
  122. .. tabs::
  123. .. code-tab:: gdscript GDScript
  124. # calculate vector from a to b
  125. var dvec = (point_b - point_a).normalized()
  126. # rotate 90 degrees
  127. var normal = Vector2(dvec.y, -dvec.x)
  128. # or alternatively
  129. # var normal = Vector2(-dvec.y, dvec.x)
  130. # depending the desired side of the normal
  131. .. code-tab:: csharp
  132. // calculate vector from a to b
  133. var dvec = (pointB - pointA).Normalized();
  134. // rotate 90 degrees
  135. var normal = new Vector2(dvec.y, -dvec.x);
  136. // or alternatively
  137. // var normal = new Vector2(-dvec.y, dvec.x);
  138. // depending the desired side of the normal
  139. The rest is the same as the previous example, either point_a or
  140. point_b will work since they are in the same plane:
  141. .. tabs::
  142. .. code-tab:: gdscript GDScript
  143. var N = normal
  144. var D = normal.dot(point_a)
  145. # this works the same
  146. # var D = normal.dot(point_b)
  147. .. code-tab:: csharp
  148. var N = normal;
  149. var D = normal.Dot(pointA);
  150. // this works the same
  151. // var D = normal.Dot(pointB);
  152. Doing the same in 3D is a little more complex and will be explained
  153. further down.
  154. Some examples of planes
  155. -----------------------
  156. Here is a simple example of what planes are useful for. Imagine you have
  157. a `convex <https://www.mathsisfun.com/definitions/convex.html>`__
  158. polygon. For example, a rectangle, a trapezoid, a triangle, or just any
  159. polygon where no faces bend inwards.
  160. For every segment of the polygon, we compute the plane that passes by
  161. that segment. Once we have the list of planes, we can do neat things,
  162. for example checking if a point is inside the polygon.
  163. We go through all planes, if we can find a plane where the distance to
  164. the point is positive, then the point is outside the polygon. If we
  165. can't, then the point is inside.
  166. .. image:: img/tutovec13.png
  167. Code should be something like this:
  168. .. tabs::
  169. .. code-tab:: gdscript GDScript
  170. var inside = true
  171. for p in planes:
  172. # check if distance to plane is positive
  173. if (p.distance_to(point) > 0):
  174. inside = false
  175. break # with one that fails, it's enough
  176. .. code-tab:: csharp
  177. var inside = true;
  178. foreach (var p in planes)
  179. {
  180. // check if distance to plane is positive
  181. if (p.DistanceTo(point) > 0)
  182. {
  183. inside = false;
  184. break; // with one that fails, it's enough
  185. }
  186. }
  187. Pretty cool, huh? But this gets much better! With a little more effort,
  188. similar logic will let us know when two convex polygons are overlapping
  189. too. This is called the Separating Axis Theorem (or SAT) and most
  190. physics engines use this to detect collision.
  191. With a point, just checking if a plane
  192. returns a positive distance is enough to tell if the point is outside.
  193. With another polygon, we must find a plane where *all* *the* *other*
  194. *polygon* *points* return a positive distance to it. This check is
  195. performed with the planes of A against the points of B, and then with
  196. the planes of B against the points of A:
  197. .. image:: img/tutovec14.png
  198. Code should be something like this:
  199. .. tabs::
  200. .. code-tab:: gdscript GDScript
  201. var overlapping = true
  202. for p in planes_of_A:
  203. var all_out = true
  204. for v in points_of_B:
  205. if (p.distance_to(v) < 0):
  206. all_out = false
  207. break
  208. if (all_out):
  209. # a separating plane was found
  210. # do not continue testing
  211. overlapping = false
  212. break
  213. if (overlapping):
  214. # only do this check if no separating plane
  215. # was found in planes of A
  216. for p in planes_of_B:
  217. var all_out = true
  218. for v in points_of_A:
  219. if (p.distance_to(v) < 0):
  220. all_out = false
  221. break
  222. if (all_out):
  223. overlapping = false
  224. break
  225. if (overlapping):
  226. print("Polygons Collided!")
  227. .. code-tab:: csharp
  228. var overlapping = true;
  229. foreach (Plane plane in planesOfA)
  230. {
  231. var allOut = true;
  232. foreach (Vector3 point in pointsOfB)
  233. {
  234. if (plane.DistanceTo(point) < 0)
  235. {
  236. allOut = false;
  237. break;
  238. }
  239. }
  240. if (allOut)
  241. {
  242. // a separating plane was found
  243. // do not continue testing
  244. overlapping = false;
  245. break;
  246. }
  247. }
  248. if (overlapping)
  249. {
  250. // only do this check if no separating plane
  251. // was found in planes of A
  252. foreach (Plane plane in planesOfB)
  253. {
  254. var allOut = true;
  255. foreach (Vector3 point in pointsOfA)
  256. {
  257. if (plane.DistanceTo(point) < 0)
  258. {
  259. allOut = false;
  260. break;
  261. }
  262. }
  263. if (allOut)
  264. {
  265. overlapping = false;
  266. break;
  267. }
  268. }
  269. }
  270. if (overlapping)
  271. {
  272. GD.Print("Polygons Collided!");
  273. }
  274. As you can see, planes are quite useful, and this is the tip of the
  275. iceberg. You might be wondering what happens with non convex polygons.
  276. This is usually just handled by splitting the concave polygon into
  277. smaller convex polygons, or using a technique such as BSP (which is not
  278. used much nowadays).
  279. Collision detection in 3D
  280. ~~~~~~~~~~~~~~~~~~~~~~~~~
  281. This is another bonus bit, a reward for being patient and keeping up
  282. with this long tutorial. Here is another piece of wisdom. This might
  283. not be something with a direct use case (Godot already does collision
  284. detection pretty well) but it's used by almost all physics engines and collision
  285. detection libraries :)
  286. Remember that converting a convex shape in 2D to an array of 2D planes
  287. was useful for collision detection? You could detect if a point was
  288. inside any convex shape, or if two 2D convex shapes were overlapping.
  289. Well, this works in 3D too, if two 3D polyhedral shapes are colliding,
  290. you won't be able to find a separating plane. If a separating plane is
  291. found, then the shapes are definitely not colliding.
  292. To refresh a bit a separating plane means that all vertices of polygon A
  293. are in one side of the plane, and all vertices of polygon B are in the
  294. other side. This plane is always one of the face-planes of either
  295. polygon A or polygon B.
  296. In 3D though, there is a problem to this approach, because it is
  297. possible that, in some cases a separating plane can't be found. This is
  298. an example of such situation:
  299. .. image:: img/tutovec22.png
  300. To avoid it, some extra planes need to be tested as separators, these
  301. planes are the cross product between the edges of polygon A and the
  302. edges of polygon B
  303. .. image:: img/tutovec23.png
  304. So the final algorithm is something like:
  305. .. tabs::
  306. .. code-tab:: gdscript GDScript
  307. var overlapping = true
  308. for p in planes_of_A:
  309. var all_out = true
  310. for v in points_of_B:
  311. if (p.distance_to(v) < 0):
  312. all_out = false
  313. break
  314. if (all_out):
  315. # a separating plane was found
  316. # do not continue testing
  317. overlapping = false
  318. break
  319. if (overlapping):
  320. # only do this check if no separating plane
  321. # was found in planes of A
  322. for p in planes_of_B:
  323. var all_out = true
  324. for v in points_of_A:
  325. if (p.distance_to(v) < 0):
  326. all_out = false
  327. break
  328. if (all_out):
  329. overlapping = false
  330. break
  331. if (overlapping):
  332. for ea in edges_of_A:
  333. for eb in edges_of_B:
  334. var n = ea.cross(eb)
  335. if (n.length() == 0):
  336. continue
  337. var max_A = -1e20 # tiny number
  338. var min_A = 1e20 # huge number
  339. # we are using the dot product directly
  340. # so we can map a maximum and minimum range
  341. # for each polygon, then check if they
  342. # overlap.
  343. for v in points_of_A:
  344. var d = n.dot(v)
  345. max_A = max(max_A, d)
  346. min_A = min(min_A, d)
  347. var max_B = -1e20 # tiny number
  348. var min_B = 1e20 # huge number
  349. for v in points_of_B:
  350. var d = n.dot(v)
  351. max_B = max(max_B, d)
  352. min_B = min(min_B, d)
  353. if (min_A > max_B or min_B > max_A):
  354. # not overlapping!
  355. overlapping = false
  356. break
  357. if (not overlapping):
  358. break
  359. if (overlapping):
  360. print("Polygons collided!")
  361. .. code-tab:: csharp
  362. var overlapping = true;
  363. foreach (Plane plane in planesOfA)
  364. {
  365. var allOut = true;
  366. foreach (Vector3 point in pointsOfB)
  367. {
  368. if (plane.DistanceTo(point) < 0)
  369. {
  370. allOut = false;
  371. break;
  372. }
  373. }
  374. if (allOut)
  375. {
  376. // a separating plane was found
  377. // do not continue testing
  378. overlapping = false;
  379. break;
  380. }
  381. }
  382. if (overlapping)
  383. {
  384. // only do this check if no separating plane
  385. // was found in planes of A
  386. foreach (Plane plane in planesOfB)
  387. {
  388. var allOut = true;
  389. foreach (Vector3 point in pointsOfA)
  390. {
  391. if (plane.DistanceTo(point) < 0)
  392. {
  393. allOut = false;
  394. break;
  395. }
  396. }
  397. if (allOut)
  398. {
  399. overlapping = false;
  400. break;
  401. }
  402. }
  403. }
  404. if (overlapping)
  405. {
  406. foreach (Vector3 edgeA in edgesOfA)
  407. {
  408. foreach (Vector3 edgeB in edgesOfB)
  409. {
  410. var normal = edgeA.Cross(edgeB);
  411. if (normal.Length() == 0)
  412. {
  413. continue;
  414. }
  415. var maxA = float.MinValue; // tiny number
  416. var minA = float.MaxValue; // huge number
  417. // we are using the dot product directly
  418. // so we can map a maximum and minimum range
  419. // for each polygon, then check if they
  420. // overlap.
  421. foreach (Vector3 point in pointsOfA)
  422. {
  423. var distance = normal.Dot(point);
  424. maxA = Mathf.Max(maxA, distance);
  425. minA = Mathf.Min(minA, distance);
  426. }
  427. var maxB = float.MinValue; // tiny number
  428. var minB = float.MaxValue; // huge number
  429. foreach (Vector3 point in pointsOfB)
  430. {
  431. var distance = normal.Dot(point);
  432. maxB = Mathf.Max(maxB, distance);
  433. minB = Mathf.Min(minB, distance);
  434. }
  435. if (minA > maxB || minB > maxA)
  436. {
  437. // not overlapping!
  438. overlapping = false;
  439. break;
  440. }
  441. }
  442. if (!overlapping)
  443. {
  444. break;
  445. }
  446. }
  447. }
  448. if (overlapping)
  449. {
  450. GD.Print("Polygons Collided!");
  451. }