vector_math.rst 28 KB

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