vector_math.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. .. _doc_vector_math:
  2. Vector math
  3. ===========
  4. Introduction
  5. ~~~~~~~~~~~~
  6. This small tutorial aims to be a short and practical introduction to
  7. vector math, useful for 3D but also 2D games. Again, vector math is not
  8. only useful for 3D but *also* 2D games. It is an amazing tool once you
  9. get the grasp of it and makes programming of complex behaviors much
  10. simpler.
  11. It often happens that young programmers rely too much on the *incorrect*
  12. math for solving a wide array of problems, for example using only
  13. trigonometry instead of vector of math for 2D games.
  14. This tutorial will focus on practical usage, with immediate application
  15. to the art of game programming.
  16. Coordinate systems (2D)
  17. ~~~~~~~~~~~~~~~~~~~~~~~
  18. Typically, we define coordinates as an (x,y) pair, x representing the
  19. horizontal offset and y the vertical one. This makes sense given the
  20. screen is just a rectangle in two dimensions. As an example, here is a
  21. position in 2D space:
  22. .. image:: /img/tutovec1.png
  23. A position can be anywhere in space. The position (0,0) has a name, it's
  24. called the **origin**. Remember this term well because it has more
  25. implicit uses later. The (0,0) of a n-dimensions coordinate system is
  26. the **origin**.
  27. In vector math, coordinates have two different uses, both equally
  28. important. They are used to represent a *position* but also a *vector*.
  29. The same position as before, when imagined as a vector, has a different
  30. meaning.
  31. .. image:: /img/tutovec2.png
  32. When imagined as a vector, two properties can be inferred, the
  33. **direction** and the **magnitude**. Every position in space can be a
  34. vector, with the exception of the **origin**. This is because
  35. coordinates (0,0) can't represent direction (magnitude 0).
  36. .. image:: /img/tutovec2b.png
  37. Direction
  38. ---------
  39. Direction is simply towards where the vector points to. Imagine an arrow
  40. that starts at the **origin** and goes towards a [STRIKEOUT:position].
  41. The tip of the arrow is in the position, so it always points outwards,
  42. away from the origin. Imagining vectors as arrows helps a lot.
  43. .. image:: /img/tutovec3b.png
  44. Magnitude
  45. ---------
  46. Finally, the length of the vector is the distance from the origin to the
  47. position. Obtaining the length from a vector is easy, just use the
  48. `Pythagorean
  49. Theorem <http://en.wikipedia.org/wiki/Pythagorean_theorem>`__.
  50. ::
  51. var len = sqrt( x*x + y*y )
  52. But... angles?
  53. --------------
  54. But why not using an *angle*? After all, we could also think of a vector
  55. as an angle and a magnitude, instead of a direction and a magnitude.
  56. Angles also are a more familiar concept.
  57. To say truth, angles are not that useful in vector math, and most of the
  58. time they are not dealt with directly. Maybe they work in 2D, but in 3D
  59. a lot of what can usually be done with angles does not work anymore.
  60. Still, using angles is still not an excuse, even for 2D. Most of what
  61. takes a lot of work with angles in 2D, is still much more natural easier
  62. to accomplish with vector math. In vector math, angles are useful only
  63. as measure, but take little part in the math. So, give up the
  64. trigonometry already, prepare to embrace vectors!
  65. In any case, obtaining an angle from a vector is easy and can be
  66. accomplished with trig... er, what was that? I mean, the
  67. :ref:`atan2() <class_@GDScript_atan2>` function.
  68. Vectors in Godot
  69. ~~~~~~~~~~~~~~~~
  70. To make examples easier, it is worth explaining how vectors are
  71. implemented in GDScript. GDscript has both
  72. :ref:`Vector2 <class_Vector2>` and :ref:`Vector3 <class_Vector3>`,
  73. for 2D and 3D math respectively. Godot uses Vector classes as both
  74. position and direction. They also contain x and y (for 2D) and x, y and
  75. z (for 3D) member variables.
  76. ::
  77. # create a vector with coordinates (2,5)
  78. var a = Vector2(2,5)
  79. # create a vector and assign x and y manually
  80. var b = Vector2()
  81. b.x = 7
  82. b.y = 8
  83. When operating with vectors, it is not necessary to operate on the
  84. members directly (in fact this is much slower). Vectors support regular
  85. arithmetic operations:
  86. ::
  87. # add a and b
  88. var c = a + b
  89. # will result in c vector, with value (9,13)
  90. It is the same as doing:
  91. ::
  92. var c = Vector2()
  93. c.x = a.x + b.x
  94. c.y = a.y + b.y
  95. Except the former is way more efficient and readable.
  96. Regular arithmetic operations such as addition, subtraction,
  97. multiplication and division are supported.
  98. Vector multiplication and division can also be mixed with single-digit
  99. numbers, also named **scalars**.
  100. ::
  101. # Multiplication of vector by scalar
  102. var c = a*2.0
  103. # will result in c vector, with value (4,10)
  104. Which is the same as doing
  105. ::
  106. var c = Vector2()
  107. c.x = a.x*2.0
  108. c.y = a.y*2.0
  109. Except, again, the former is way more efficient and readable.
  110. Perpendicular vectors
  111. ~~~~~~~~~~~~~~~~~~~~~
  112. Rotating a 2D vector 90° degrees to either side, left or right, is
  113. really easy, just swap x and y, then
  114. negate either x or y (direction of rotation depends on which is
  115. negated).
  116. .. image:: /img/tutovec15.png
  117. Example:
  118. ::
  119. var v = Vector2(0,1)
  120. # rotate right (clockwise)
  121. var v_right = Vector2(-v.y, v.x)
  122. # rotate left (counter-clockwise)
  123. var v_right = Vector2(v.y, -v.x)
  124. This is a handy trick that is often of use. It is impossible to do with
  125. 3D vectors, because there are an infinite amount of perpendicular
  126. vectors.
  127. Unit vectors
  128. ~~~~~~~~~~~~
  129. Ok, so we know what a vector is. It has a **direction** and a
  130. **magnitude**. We also know how to use them in Godot. The next step is
  131. learning about **unit vectors**. Any vector with **magnitude** of length
  132. 1 is considered a **unit vector**. In 2D, imagine drawing a circle of
  133. radius one. That circle contains all unit vectors in existence for 2
  134. dimensions:
  135. .. image:: /img/tutovec3.png
  136. So, what is so special about unit vectors? Unit vectors are amazing. In
  137. other words, unit vectors have **several, very useful properties**.
  138. Can't wait to know more about the fantastic properties of unit vectors,
  139. but one step at a time. So, how is a unit vector created from a regular
  140. vector?
  141. Normalization
  142. -------------
  143. Taking any vector and reducing it's **magnitude** to 1.0 while keeping
  144. it's **direction** is called **normalization**. Normalization is
  145. performed by dividing the x and y (and z in 3D) components of a vector
  146. by it's magnitude:
  147. ::
  148. var a = Vector2(2,4)
  149. var m = sqrt(a.x*a.x + a.y*a.y)
  150. a.x /= m
  151. a.y /= m
  152. As you might have guessed, if the vector has magnitude 0 (meaning, it's
  153. not a vector but the **origin** also called *null vector*), a division
  154. by zero occurs and the universe goes through a second big bang, except
  155. in reverse polarity and then back. As a result, humanity is safe but
  156. Godot will print an error. Remember! Vector(0,0) can't be normalized!.
  157. Of course, Vector2 and Vector3 already provide a method to do this:
  158. ::
  159. a = a.normalized()
  160. Dot product
  161. ~~~~~~~~~~~
  162. OK, the **dot product** is the most important part of vector math.
  163. Without the dot product, Quake would have never been made. This is the
  164. most important section of the tutorial, so make sure to grasp it
  165. properly. Most people trying to understand vector math give up here
  166. because, despite how simple it is, they can't make head or tails from
  167. it. Why? Here's why, it's because...
  168. The dot product takes two vectors and returns a **scalar**:
  169. ::
  170. var s = a.x*b.x + a.y*b.y
  171. Yes, pretty much that. Multiply **x** from vector **a** by **x** from
  172. vector **b**. Do the same with y and add it together. In 3D it's pretty
  173. much the same:
  174. ::
  175. var s = a.x*b.x + a.y*b.y + a.z*b.z
  176. I know, it's totally meaningless! you can even do it with a built-in
  177. function:
  178. ::
  179. var s = a.dot(b)
  180. The order of two vectors does *not* matter, ``a.dot(b)`` returns the
  181. same value as ``b.dot(a)``.
  182. This is where despair begins and books and tutorials show you this
  183. formula:
  184. .. image:: /img/tutovec4.png
  185. And you realize it's time to give up making 3D games or complex 2D
  186. games. How can something so simple be so complex? Someone else will have
  187. to make the next Zelda or Call of Duty. Top down RPGs don't look so bad
  188. after all. Yeah I hear someone did pretty will with one of those on
  189. Steam...
  190. So this is your moment, this is your time to shine. **DO NOT GIVE UP**!
  191. At this point, this tutorial will take a sharp turn and focus on what
  192. makes the dot product useful. This is, **why** it is useful. We will
  193. focus one by one in the use cases for the dot product, with real-life
  194. applications. No more formulas that don't make any sense. Formulas will
  195. make sense *once you learn* why do they exist for.
  196. Siding
  197. ------
  198. The first useful and most important property of the dot product is to
  199. check what side stuff is looking at. Let's imagine we have any two
  200. vectors, **a** and **b**. Any **direction** or **magnitude** (neither
  201. **origin**). Does not matter what they are, but let's imagine we compute
  202. the dot product between them.
  203. ::
  204. var s = a.dot(b)
  205. The operation will return a single floating point number (but since we
  206. are in vector world, we call them **scalar**, will keep using that term
  207. from now on). This number will tell us the following:
  208. - If the number is greater than zero, both are looking towards the same
  209. direction (the angle between them is < 90° degrees).
  210. - If the number is less than zero, both are looking towards opposite
  211. direction (the angle between them is > 90° degrees).
  212. - If the number is zero, vectors are shaped in L (the angle between
  213. them *is* 90° degrees).
  214. .. image:: /img/tutovec5.png
  215. So let's think of a real use-case scenario. Imagine Snake is going
  216. through a forest, and then there is an enemy nearby. How can we quickly
  217. tell if the enemy has seen discovered Snake? In order to discover him,
  218. the enemy must be able to *see* Snake. Let's say, then that:
  219. - Snake is in position **A**.
  220. - The enemy is in position **B**.
  221. - The enemy is *facing* towards direction vector **F**.
  222. .. image:: /img/tutovec6.png
  223. So, let's create a new vector **BA** that goes from the guard (**B**) to
  224. Snake (**A**), by subtracting the two:
  225. ::
  226. var BA = A - B
  227. .. image:: /img/tutovec7.png
  228. Ideally, if the guard was looking straight towards snake, to make eye to
  229. eye contact, it would do it in the same direction as vector BA.
  230. If the dot product between **F** and **BA** is greater than 0, then
  231. Snake will be discovered. This happens because we will be able to tell
  232. that the guard is facing towards him:
  233. ::
  234. if (BA.dot(F) > 0):
  235. print("!")
  236. Seems Snake is safe so far.
  237. Siding with unit vectors
  238. ~~~~~~~~~~~~~~~~~~~~~~~~
  239. Ok, so now we know that dot product between two vectors will let us know
  240. if they are looking towards the same side, opposite sides or are just
  241. perpendicular to each other.
  242. This works the same with all vectors, no matter the magnitude so **unit
  243. vectors** are not the exception. However, using the same property with
  244. unit vectors yields an even more interesting result, as an extra
  245. property is added:
  246. - If both vectors are facing towards the exact same direction (parallel
  247. to each other, angle between them is 0°), the resulting scalar is
  248. **1**.
  249. - If both vectors are facing towards the exact opposite direction
  250. (parallel to each other, but angle between them is 180°), the
  251. resulting scalar is **-1**.
  252. This means that dot product between unit vectors is always between the
  253. range of 1 and -1. So Again...
  254. - If their angle is **0°** dot product is **1**.
  255. - If their angle is **90°**, then dot product is **0**.
  256. - If their angle is **180°**, then dot product is **-1**.
  257. Uh.. this is oddly familiar... seen this before... where?
  258. Let's take two unit vectors. The first one is pointing up, the second
  259. too but we will rotate it all the way from up (0°) to down (180°
  260. degrees)...
  261. .. image:: /img/tutovec8.png
  262. While plotting the resulting scalar!
  263. .. image:: /img/tutovec9.png
  264. Aha! It all makes sense now, this is a
  265. `Cosine <http://mathworld.wolfram.com/Cosine.html>`__ function!
  266. We can say that, then, as a rule...
  267. The **dot product** between two **unit vectors** is the **cosine** of
  268. the **angle** between those two vectors. So, to obtain the angle between
  269. two vectors, we must do:
  270. ::
  271. var angle_in_radians = acos( a.dot(b) )
  272. What is this useful for? Well obtaining the angle directly is probably
  273. not as useful, but just being able to tell the angle is useful for
  274. reference. One example is in the `Kinematic
  275. Character <https://github.com/godotengine/godot/blob/master/demos/2d/kinematic_char/player.gd#L879>`__
  276. demo, when the character moves in a certain direction then we hit an
  277. object. How to tell if what we hit is the floor?
  278. By comparing the normal of the collision point with a previously
  279. computed angle.
  280. The beauty of this is that the same code works exactly the same and
  281. without modification in
  282. `3D <https://github.com/godotengine/godot/blob/master/demos/3d/kinematic_char/cubio.gd#L57>`__.
  283. Vector math is, in a great deal, dimension-amount-independent, so adding
  284. or removing an axis only adds very little complexity.
  285. Planes
  286. ~~~~~~
  287. The dot product has another interesting property with unit vectors.
  288. Imagine that perpendicular to that vector (and through the origin)
  289. passes a plane. Planes divide the entire space into positive
  290. (over the plane) and negative (under the plane), and (contrary to
  291. popular belief) you can also use their math in 2D:
  292. .. image:: /img/tutovec10.png
  293. Unit vectors that are perpendicular to a surface (so, they describe the
  294. orientation of the surface) are called **unit normal vectors**. Though,
  295. usually they are just abbreviated as \*normalsÄ. Normals appear in
  296. planes, 3D geometry (to determine where each face or vertex is siding),
  297. etc. A **normal** *is* a **unit vector**, but it's called *normal*
  298. because of it's usage. (Just like we call Origin to (0,0)!).
  299. It's as simple as it looks. The plane passes by the origin and the
  300. surface of it is perpendicular to the unit vector (or *normal*). The
  301. side towards the vector points to is the positive half-space, while the
  302. other side is the negative half-space. In 3D this is exactly the same,
  303. except that the plane is an infinite surface (imagine an infinite, flat
  304. sheet of paper that you can orient and is pinned to the origin) instead
  305. of a line.
  306. Distance to plane
  307. -----------------
  308. Now that it's clear what a plane is, let's go back to the dot product.
  309. The dot product between a **unit vector** and any **point in space**
  310. (yes, this time we do dot product between vector and position), returns
  311. the **distance from the point to the plane**:
  312. ::
  313. var distance = normal.dot(point)
  314. But not just the absolute distance, if the point is in the negative half
  315. space the distance will be negative, too:
  316. .. image:: /img/tutovec11.png
  317. This allows us to tell which side of the plane a point is.
  318. Away from the origin
  319. --------------------
  320. I know what you are thinking! So far this is nice, but *real* planes are
  321. everywhere in space, not only passing through the origin. You want real
  322. *plane* action and you want it *now*.
  323. Remember that planes not only split space in two, but they also have
  324. *polarity*. This means that it is possible to have perfectly overlapping
  325. planes, but their negative and positive half-spaces are swapped.
  326. With this in mind, let's describe a full plane as a **normal** *N* and a
  327. **distance from the origin** scalar *D*. Thus, our plane is represented
  328. by N and D. For example:
  329. .. image:: /img/tutovec12.png
  330. For 3D math, Godot provides a :ref:`Plane <class_Plane>`
  331. built-in type that handles this.
  332. Basically, N and D can represent any plane in space, be it for 2D or 3D
  333. (depending on the amount of dimensions of N) and the math is the same
  334. for both. It's the same as before, but D id the distance from the origin
  335. to the plane, travelling in N direction. As an example, imagine you want
  336. to reach a point in the plane, you will just do:
  337. ::
  338. var point_in_plane = N*D
  339. This will stretch (resize) the normal vector and make it touch the
  340. plane. This math might seem confusing, but it's actually much simpler
  341. than it seems. If we want to tell, again, the distance from the point to
  342. the plane, we do the same but adjusting for distance:
  343. ::
  344. var distance = N.dot(point) - D
  345. This will, again, return either a positive or negative distance.
  346. Flipping the polarity of the plane is also very simple, just negate both
  347. N and D. this will result in a plane in the same position, but with
  348. inverted negative and positive half spaces:
  349. ::
  350. N = -N
  351. D = -D
  352. Of course, Godot implements this operator in :ref:`Plane <class_Plane>`,
  353. so doing:
  354. ::
  355. var inverted_plane = -plane
  356. Will work as expected.
  357. So, remember, a plane is just that and it's main practical use is
  358. calculating the distance to it. So, why is it useful to calculate the
  359. distance from a point to a plane? It's extremely useful! Let's see some
  360. simple examples..
  361. Constructing a plane in 2D
  362. --------------------------
  363. Planes clearly don't come out of nowhere, so they must be built.
  364. Constructing them in 2D is easy, this can be done from either a normal
  365. (unit vector) and a point, or from two points in space.
  366. In the case of a normal and a point, most of the work is done, as the
  367. normal is already computed, so just calculate D from the dot product of
  368. the normal and the point.
  369. ::
  370. var N = normal
  371. var D = normal.dot(point)
  372. For two points in space, there are actually two planes that pass through
  373. them, sharing the same space but with normal pointing to the opposite
  374. directions. To compute the normal from the two points, the direction
  375. vector must be obtained first, and then it needs to be rotated 90°
  376. degrees to either side:
  377. ::
  378. # calculate vector from a to b
  379. var dvec = (point_b - point_a).normalized()
  380. # rotate 90 degrees
  381. var normal = Vector2(dvec.y,-dev.x)
  382. # or alternatively
  383. # var normal = Vector2(-dvec.y,dev.x)
  384. # depending the desired side of the normal
  385. The rest is the same as the previous example, either point_a or
  386. point_b will work since they are in the same plane:
  387. ::
  388. var N = normal
  389. var D = normal.dot(point_a)
  390. # this works the same
  391. # var D = normal.dot(point_b)
  392. Doing the same in 3D is a little more complex and will be explained
  393. further down.
  394. Some examples of planes
  395. -----------------------
  396. Here is a simple example of what planes are useful for. Imagine you have
  397. a `convex <http://www.mathsisfun.com/definitions/convex.html>`__
  398. polygon. For example, a rectangle, a trapezoid, a triangle, or just any
  399. polygon where faces that don't bend inwards.
  400. For every segment of the polygon, we compute the plane that passes by
  401. that segment. Once we have the list of planes, we can do neat things,
  402. for example checking if a point is inside the polygon.
  403. We go through all planes, if we can find a plane where the distance to
  404. the point is positive, then the point is outside the polygon. If we
  405. can't, then the point is inside.
  406. .. image:: /img/tutovec13.png
  407. Code should be something like this:
  408. ::
  409. var inside = true
  410. for p in planes:
  411. # check if distance to plane is positive
  412. if (N.dot(point) - D > 0):
  413. inside = false
  414. break # with one that fails, it's enough
  415. Pretty cool, huh? But this gets much better! With a little more effort,
  416. similar logic will let us know when two convex polygons are overlapping
  417. too. This is called the Separating Axis Theorem (or SAT) and most
  418. physics engines use this to detect collision.
  419. The idea is really simple! With a point, just checking if a plane
  420. returns a positive distance is enough to tell if the point is outside.
  421. With another polygon, we must find a plane where *all the **other**
  422. polygon points* return a positive distance to it. This check is
  423. performed with the planes of A against the points of B, and then with
  424. the planes of B against the points of A:
  425. .. image:: /img/tutovec14.png
  426. Code should be something like this:
  427. ::
  428. var overlapping = true
  429. for p in planes_of_A:
  430. var all_out = true
  431. for v in points_of_B:
  432. if (p.distance_to(v) < 0):
  433. all_out = false
  434. break
  435. if (all_out):
  436. # a separating plane was found
  437. # do not continue testing
  438. overlapping = false
  439. break
  440. if (overlapping):
  441. # only do this check if no separating plane
  442. # was found in planes of A
  443. for p in planes_of_B:
  444. var all_out = true
  445. for v in points_of_A:
  446. if (p.distance_to(v) < 0):
  447. all_out = false
  448. break
  449. if (all_out):
  450. overlapping = false
  451. break
  452. if (overlapping):
  453. print("Polygons Collided!")
  454. As you can see, planes are quite useful, and this is the tip of the
  455. iceberg. You might be wondering what happens with non convex polygons.
  456. This is usually just handled by splitting the concave polygon into
  457. smaller convex polygons, or using a technique such as BSP (which is not
  458. used much nowadays).
  459. Cross product
  460. -------------
  461. Quite a lot can be done with the dot product! But the party would not be
  462. complete without the cross product. Remember back at the beginning of
  463. this tutorial? Specifically how to obtain a perpendicular (rotated 90
  464. degrees) vector by swapping x and y, then negating either of them for
  465. right (clockwise) or left (counter-clockwise) rotation? That ended up
  466. being useful for calculating a 2D plane normal from two points.
  467. As mentioned before, no such thing exists in 3D because a 3D vector has
  468. infinite perpendicular vectors. It would also not make sense to obtain a
  469. 3D plane from 2 points, as 3 points are needed instead.
  470. To aid in this kind stuff, the brightest minds of humanity's top
  471. mathematicians brought us the **cross product**.
  472. The cross product takes two vectors and returns another vector. The
  473. returned third vector is always perpendicular to the first two. The
  474. source vectors, of course, must not be the same, and must not be
  475. parallel or opposite, else the resulting vector will be (0,0,0):
  476. .. image:: /img/tutovec16.png
  477. The formula for the cross product is:
  478. ::
  479. var c = Vector3()
  480. c.x = (a.y + b.z) - (a.z + b.y)
  481. c.y = (a.z + b.x) - (a.x + b.z)
  482. c.z = (a.x + b.y) - (a.y + b.x)
  483. This can be simplified, in Godot, to:
  484. ::
  485. var c = a.cross(b)
  486. However, unlike the dot product, doing ``a.cross(b)`` and ``b.cross(a)``
  487. will yield different results. Specifically, the returned vector will be
  488. negated in the second case. As you might have realized, this coincides
  489. with creating perpendicular vectors in 2D. In 3D, there are also two
  490. possible perpendicular vectors to a pair of 2D vectors.
  491. Also, the resulting cross product of two unit vectors is *not* a unit
  492. vector. Result will need to be renormalized.
  493. Area of a triangle
  494. ~~~~~~~~~~~~~~~~~~
  495. Cross product can be used to obtain the surface area of a triangle in
  496. 3D. Given a triangle consisting of 3 points, **A**, **B** and **C**:
  497. .. image:: /img/tutovec17.png
  498. Take any of them as a pivot and compute the adjacent vectors to the
  499. other two points. As example, we will use B as a pivot:
  500. ::
  501. var BA = A - B
  502. var BC = C - B
  503. .. image:: /img/tutovec18.png
  504. Compute the cross product between **BA** and **BC** to obtain the
  505. perpendicular vector **P**:
  506. ::
  507. var P = BA.cross(BC)
  508. .. image:: /img/tutovec19.png
  509. The length (magnitude) of **P** is the surface area of the parallelogram
  510. built by the two vectors **BA** and **BC**, therefore the surface area
  511. of the triangle is half of it.
  512. ::
  513. var area = P.length()/2
  514. Plane of the triangle
  515. ~~~~~~~~~~~~~~~~~~~~~
  516. With **P** computed from the previous step, normalize it to get the
  517. normal of the plane.
  518. ::
  519. var N = P.normalized()
  520. And obtain the distance by doing the dot product of P with any of the 3
  521. points of the **ABC** triangle:
  522. ::
  523. var D = P.dot(A)
  524. Fantastic! you computed the plane from a triangle!
  525. Here's some useful info (that you can find in Godot source code anyway).
  526. Computing a plane from a triangle can result in 2 planes, so a sort of
  527. convention needs to be set. This usually depends (in video games and 3D
  528. visualization) to use the front-facing side of the triangle.
  529. In Godot, front-facing triangles are those that, when looking at the
  530. camera, are in clockwise order. Triangles that look Counter-clockwise
  531. when looking at the camera are not drawn (this helps to draw less, so
  532. the back-part of the objects is not drawn).
  533. To make it a little clearer, in the image below, the triangle **ABC**
  534. appears clock-wise when looked at from the *Front Camera*, but to the
  535. *Rear Camera* it appears counter-clockwise so it will not be drawn.
  536. .. image:: /img/tutovec20.png
  537. Normals of triangles often are sided towards the direction they can be
  538. viewed from, so in this case, the normal of triangle ABC would point
  539. towards the front camera:
  540. .. image:: /img/tutovec21.png
  541. So, to obtain N, the correct formula is:
  542. ::
  543. # clockwise normal from triangle formula
  544. var N = (A-C).cross(A-B).normalized()
  545. # for counter-clockwise:
  546. # var N = (A-B).cross(A-C).normalized()
  547. var D = N.dot(A)
  548. Collision detection in 3D
  549. ~~~~~~~~~~~~~~~~~~~~~~~~~
  550. This is another bonus bit, a reward for being patient and keeping up
  551. with this long tutorial. Here is another piece of wisdom. This maybe is
  552. not something with a direct use case (Godot already does collision
  553. detection pretty well) but It's a really cool algorithm to understand
  554. anyway, because it's used by almost all physics engines and collision
  555. detection libraries :)
  556. Remember that converting a convex shape in 2D to an array of 2D planes
  557. was useful for collision detection? You could detect if a point was
  558. inside any convex shape, or if two 2D convex shapes were overlapping.
  559. Well, this works in 3D too, if two 3D polyhedral shapes are colliding,
  560. you won't be able to find a separating plane. If a separating plane is
  561. found, then the shapes are definitely not colliding.
  562. To refresh a bit a separating plane means that all vertices of polygon A
  563. are in one side of the plane, and all vertices of polygon B are in the
  564. other side. This plane is always one of the face-planes of either
  565. polygon A or polygon B.
  566. In 3D though, there is a problem to this approach, because it is
  567. possible that, in some cases a separating plane can't be found. This is
  568. an example of such situation:
  569. .. image:: /img/tutovec22.png
  570. To avoid it, some extra planes need to be tested as separators, these
  571. planes are the cross product between the edges of polygon A and the
  572. edges of polygon B
  573. .. image:: /img/tutovec23.png
  574. So the final algorithm is something like:
  575. ::
  576. var overlapping = true
  577. for p in planes_of_A:
  578. var all_out = true
  579. for v in points_of_B:
  580. if (p.distance_to(v) < 0):
  581. all_out = false
  582. break
  583. if (all_out):
  584. # a separating plane was found
  585. # do not continue testing
  586. overlapping = false
  587. break
  588. if (overlapping):
  589. # only do this check if no separating plane
  590. # was found in planes of A
  591. for p in planes_of_B:
  592. var all_out = true
  593. for v in points_of_A:
  594. if (p.distance_to(v) < 0):
  595. all_out = false
  596. break
  597. if (all_out):
  598. overlapping = false
  599. break
  600. if (overlapping):
  601. for ea in edges_of_A:
  602. for eb in edges_of_B:
  603. var n = ea.cross(eb)
  604. if (n.length() == 0):
  605. continue
  606. var max_A = -1e20 # tiny number
  607. var min_A = 1e20 # huge number
  608. # we are using the dot product directly
  609. # so we can map a maximum and minimum range
  610. # for each polygon, then check if they
  611. # overlap.
  612. for v in points_of_A:
  613. var d = n.dot(v)
  614. if (d > max_A):
  615. max_A = d
  616. if (d < min_A):
  617. min_A = d
  618. var max_B = -1e20 # tiny number
  619. var min_B = 1e20 # huge number
  620. for v in points_of_B:
  621. var d = n.dot(v)
  622. if (d > max_B):
  623. max_B = d
  624. if (d < min_B):
  625. min_B = d
  626. if (min_A > max_B or min_B > max_A):
  627. # not overlapping!
  628. overlapping = false
  629. break
  630. if (not overlapping):
  631. break
  632. if (overlapping):
  633. print("Polygons collided!")
  634. This was all! Hope it was helpful, and please give feedback and let know
  635. if something in this tutorial is not clear! You should be now ready for
  636. the next challenge... :ref:`doc_matrices_and_transforms`!