1
0

scenegraph.html 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Scene Graph</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – Scene Graph">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="../resources/lesson.css">
  12. <link rel="stylesheet" href="../resources/lang.css">
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../../build/three.module.js"
  17. }
  18. }
  19. </script>
  20. </head>
  21. <body>
  22. <div class="container">
  23. <div class="lesson-title">
  24. <h1>Scene Graph</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>This article is part of a series of articles about three.js. The
  29. first article is <a href="fundamentals.html">three.js fundamentals</a>. If
  30. you haven't read that yet you might want to consider starting there.</p>
  31. <p>Three.js's core is arguably its scene graph. A scene graph in a 3D
  32. engine is a hierarchy of nodes in a graph where each node represents
  33. a local space.</p>
  34. <p><img src="../resources/images/scenegraph-generic.svg" align="center"></p>
  35. <p>That's kind of abstract so let's try to give some examples.</p>
  36. <p>One example might be solar system, sun, earth, moon.</p>
  37. <p><img src="../resources/images/scenegraph-solarsystem.svg" align="center"></p>
  38. <p>The Earth orbits the Sun. The Moon orbits the Earth. The Moon
  39. moves in a circle around the Earth. From the Moon's point of
  40. view it's rotating in the "local space" of the Earth. Even though
  41. its motion relative to the Sun is some crazy spirograph like
  42. curve from the Moon's point of view it just has to concern itself with rotating
  43. around the Earth's local space.</p>
  44. <p></p><div class="threejs_diagram_container">
  45. <iframe class="threejs_diagram " style="width: 400px; height: 300px;" src="/manual/foo/../resources/moon-orbit.html"></iframe>
  46. </div>
  47. <p></p>
  48. <p>To think of it another way, you living on the Earth do not have to think
  49. about the Earth's rotation on its axis nor its rotation around the
  50. Sun. You just walk or drive or swim or run as though the Earth is
  51. not moving or rotating at all. You walk, drive, swim, run, and live
  52. in the Earth's "local space" even though relative to the sun you are
  53. spinning around the earth at around 1000 miles per hour and around
  54. the sun at around 67,000 miles per hour. Your position in the solar
  55. system is similar to that of the moon above but you don't have to concern
  56. yourself. You just worry about your position relative to the earth in its
  57. "local space".</p>
  58. <p>Let's take it one step at a time. Imagine we want to make
  59. a diagram of the sun, earth, and moon. We'll start with the sun by
  60. just making a sphere and putting it at the origin. Note: We're using
  61. sun, earth, moon as a demonstration of how to use a scene graph. Of course
  62. the real sun, earth, and moon use physics but for our purposes we'll
  63. fake it with a scene graph.</p>
  64. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// an array of objects whose rotation to update
  65. const objects = [];
  66. // use just one sphere for everything
  67. const radius = 1;
  68. const widthSegments = 6;
  69. const heightSegments = 6;
  70. const sphereGeometry = new THREE.SphereGeometry(
  71. radius, widthSegments, heightSegments);
  72. const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00});
  73. const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
  74. sunMesh.scale.set(5, 5, 5); // make the sun large
  75. scene.add(sunMesh);
  76. objects.push(sunMesh);
  77. </pre>
  78. <p>We're using a really low-polygon sphere. Only 6 subdivisions around its equator.
  79. This is so it's easy to see the rotation.</p>
  80. <p>We're going to reuse the same sphere for everything so we'll set a scale
  81. for the sun mesh of 5x.</p>
  82. <p>We also set the phong material's <code class="notranslate" translate="no">emissive</code> property to yellow. A phong material's
  83. emissive property is basically the color that will be drawn with no light hitting
  84. the surface. Light is added to that color.</p>
  85. <p>Let's also put a single point light in the center of the scene. We'll go into more
  86. details about point lights later but for now the simple version is a point light
  87. represents light that emanates from a single point.</p>
  88. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  89. const color = 0xFFFFFF;
  90. const intensity = 3;
  91. const light = new THREE.PointLight(color, intensity);
  92. scene.add(light);
  93. }
  94. </pre>
  95. <p>To make it easy to see we're going to put the camera directly above the origin
  96. looking down. The easiest way to do that is to use the <code class="notranslate" translate="no">lookAt</code> function. The <code class="notranslate" translate="no">lookAt</code>
  97. function will orient the camera from its position to "look at" the position
  98. we pass to <code class="notranslate" translate="no">lookAt</code>. Before we do that though we need to tell the camera
  99. which way the top of the camera is facing or rather which way is "up" for the
  100. camera. For most situations positive Y being up is good enough but since
  101. we are looking straight down we need to tell the camera that positive Z is up.</p>
  102. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  103. camera.position.set(0, 50, 0);
  104. camera.up.set(0, 0, 1);
  105. camera.lookAt(0, 0, 0);
  106. </pre>
  107. <p>In the render loop, adapted from previous examples, we're rotating all
  108. objects in our <code class="notranslate" translate="no">objects</code> array with this code.</p>
  109. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">objects.forEach((obj) =&gt; {
  110. obj.rotation.y = time;
  111. });
  112. </pre>
  113. <p>Since we added the <code class="notranslate" translate="no">sunMesh</code> to the <code class="notranslate" translate="no">objects</code> array it will rotate.</p>
  114. <p></p><div translate="no" class="threejs_example_container notranslate">
  115. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-sun.html"></iframe></div>
  116. <a class="threejs_center" href="/manual/examples/scenegraph-sun.html" target="_blank">click here to open in a separate window</a>
  117. </div>
  118. <p></p>
  119. <p>Now let's add in the earth.</p>
  120. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
  121. const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
  122. earthMesh.position.x = 10;
  123. scene.add(earthMesh);
  124. objects.push(earthMesh);
  125. </pre>
  126. <p>We make a material that is blue but we gave it a small amount of <em>emissive</em> blue
  127. so that it will show up against our black background.</p>
  128. <p>We use the same <code class="notranslate" translate="no">sphereGeometry</code> with our new blue <code class="notranslate" translate="no">earthMaterial</code> to make
  129. an <code class="notranslate" translate="no">earthMesh</code>. We position that 10 units to the left of the sun
  130. and add it to the scene. Since we added it to our <code class="notranslate" translate="no">objects</code> array it will
  131. rotate too.</p>
  132. <p></p><div translate="no" class="threejs_example_container notranslate">
  133. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-sun-earth.html"></iframe></div>
  134. <a class="threejs_center" href="/manual/examples/scenegraph-sun-earth.html" target="_blank">click here to open in a separate window</a>
  135. </div>
  136. <p></p>
  137. <p>You can see both the sun and the earth are rotating but the earth is not
  138. going around the sun. Let's make the earth a child of the sun</p>
  139. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-scene.add(earthMesh);
  140. +sunMesh.add(earthMesh);
  141. </pre>
  142. <p>and...</p>
  143. <p></p><div translate="no" class="threejs_example_container notranslate">
  144. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-sun-earth-orbit.html"></iframe></div>
  145. <a class="threejs_center" href="/manual/examples/scenegraph-sun-earth-orbit.html" target="_blank">click here to open in a separate window</a>
  146. </div>
  147. <p></p>
  148. <p>What happened? Why is the earth the same size as the sun and why is it so far away?
  149. I actually had to move the camera from 50 units above to 150 units above to see the earth.</p>
  150. <p>We made the <code class="notranslate" translate="no">earthMesh</code> a child of the <code class="notranslate" translate="no">sunMesh</code>. The <code class="notranslate" translate="no">sunMesh</code> has
  151. its scale set to 5x with <code class="notranslate" translate="no">sunMesh.scale.set(5, 5, 5)</code>. That means the
  152. <code class="notranslate" translate="no">sunMesh</code>s local space is 5 times as big. Anything put in that space
  153. will be multiplied by 5. That means the earth is now 5x larger and
  154. its distance from the sun (<code class="notranslate" translate="no">earthMesh.position.x = 10</code>) is also
  155. 5x as well.</p>
  156. <p> Our scene graph currently looks like this</p>
  157. <p><img src="../resources/images/scenegraph-sun-earth.svg" align="center"></p>
  158. <p>To fix it let's add an empty scene graph node. We'll parent both the sun and the earth
  159. to that node.</p>
  160. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const solarSystem = new THREE.Object3D();
  161. +scene.add(solarSystem);
  162. +objects.push(solarSystem);
  163. const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00});
  164. const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
  165. sunMesh.scale.set(5, 5, 5);
  166. -scene.add(sunMesh);
  167. +solarSystem.add(sunMesh);
  168. objects.push(sunMesh);
  169. const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
  170. const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
  171. earthMesh.position.x = 10;
  172. -sunMesh.add(earthMesh);
  173. +solarSystem.add(earthMesh);
  174. objects.push(earthMesh);
  175. </pre>
  176. <p>Here we made an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>. Like a <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> it is also a node in the scene graph
  177. but unlike a <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> it has no material or geometry. It just represents a local space.</p>
  178. <p>Our new scene graph looks like this</p>
  179. <p><img src="../resources/images/scenegraph-sun-earth-fixed.svg" align="center"></p>
  180. <p>Both the <code class="notranslate" translate="no">sunMesh</code> and the <code class="notranslate" translate="no">earthMesh</code> are children of the <code class="notranslate" translate="no">solarSystem</code>. All 3
  181. are being rotated and now because the <code class="notranslate" translate="no">earthMesh</code> is not a child of the <code class="notranslate" translate="no">sunMesh</code>
  182. it is no longer scaled by 5x.</p>
  183. <p></p><div translate="no" class="threejs_example_container notranslate">
  184. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-sun-earth-orbit-fixed.html"></iframe></div>
  185. <a class="threejs_center" href="/manual/examples/scenegraph-sun-earth-orbit-fixed.html" target="_blank">click here to open in a separate window</a>
  186. </div>
  187. <p></p>
  188. <p>Much better. The earth is smaller than the sun and it's rotating around the sun
  189. and rotating itself.</p>
  190. <p>Continuing that same pattern let's add a moon.</p>
  191. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const earthOrbit = new THREE.Object3D();
  192. +earthOrbit.position.x = 10;
  193. +solarSystem.add(earthOrbit);
  194. +objects.push(earthOrbit);
  195. const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
  196. const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
  197. -earthMesh.position.x = 10; // note that this offset is already set in its parent's THREE.Object3D object "earthOrbit"
  198. -solarSystem.add(earthMesh);
  199. +earthOrbit.add(earthMesh);
  200. objects.push(earthMesh);
  201. +const moonOrbit = new THREE.Object3D();
  202. +moonOrbit.position.x = 2;
  203. +earthOrbit.add(moonOrbit);
  204. +const moonMaterial = new THREE.MeshPhongMaterial({color: 0x888888, emissive: 0x222222});
  205. +const moonMesh = new THREE.Mesh(sphereGeometry, moonMaterial);
  206. +moonMesh.scale.set(.5, .5, .5);
  207. +moonOrbit.add(moonMesh);
  208. +objects.push(moonMesh);
  209. </pre>
  210. <p>Again we added more invisible scene graph nodes. The first, an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> called <code class="notranslate" translate="no">earthOrbit</code>
  211. and added both the <code class="notranslate" translate="no">earthMesh</code> and the <code class="notranslate" translate="no">moonOrbit</code> to it, also new. We then added the <code class="notranslate" translate="no">moonMesh</code>
  212. to the <code class="notranslate" translate="no">moonOrbit</code>. The new scene graph looks like this.</p>
  213. <p><img src="../resources/images/scenegraph-sun-earth-moon.svg" align="center"></p>
  214. <p>and here's that</p>
  215. <p></p><div translate="no" class="threejs_example_container notranslate">
  216. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-sun-earth-moon.html"></iframe></div>
  217. <a class="threejs_center" href="/manual/examples/scenegraph-sun-earth-moon.html" target="_blank">click here to open in a separate window</a>
  218. </div>
  219. <p></p>
  220. <p>You can see the moon follows the spirograph pattern shown at the top
  221. of this article but we didn't have to manually compute it. We just
  222. setup our scene graph to do it for us.</p>
  223. <p>It is often useful to draw something to visualize the nodes in the scene graph.
  224. Three.js has some helpful ummmm, helpers to ummm, ... help with this.</p>
  225. <p>One is called an <a href="/docs/#api/en/helpers/AxesHelper"><code class="notranslate" translate="no">AxesHelper</code></a>. It draws 3 lines representing the local
  226. <span style="color:red">X</span>,
  227. <span style="color:green">Y</span>, and
  228. <span style="color:blue">Z</span> axes. Let's add one to every node we
  229. created.</p>
  230. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// add an AxesHelper to each node
  231. objects.forEach((node) =&gt; {
  232. const axes = new THREE.AxesHelper();
  233. axes.material.depthTest = false;
  234. axes.renderOrder = 1;
  235. node.add(axes);
  236. });
  237. </pre>
  238. <p>On our case we want the axes to appear even though they are inside the spheres.
  239. To do this we set their material's <code class="notranslate" translate="no">depthTest</code> to false which means they will
  240. not check to see if they are drawing behind something else. We also
  241. set their <code class="notranslate" translate="no">renderOrder</code> to 1 (the default is 0) so that they get drawn after
  242. all the spheres. Otherwise a sphere might draw over them and cover them up.</p>
  243. <p></p><div translate="no" class="threejs_example_container notranslate">
  244. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-sun-earth-moon-axes.html"></iframe></div>
  245. <a class="threejs_center" href="/manual/examples/scenegraph-sun-earth-moon-axes.html" target="_blank">click here to open in a separate window</a>
  246. </div>
  247. <p></p>
  248. <p>We can see the
  249. <span style="color:red">x (red)</span> and
  250. <span style="color:blue">z (blue)</span> axes. Since we are looking
  251. straight down and each of our objects is only rotating around its
  252. y axis we don't see much of the <span style="color:green">y (green)</span> axes.</p>
  253. <p>It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the <code class="notranslate" translate="no">sunMesh</code>
  254. and the <code class="notranslate" translate="no">solarSystem</code> are at the same position. Similarly the <code class="notranslate" translate="no">earthMesh</code> and
  255. <code class="notranslate" translate="no">earthOrbit</code> are at the same position. Let's add some simple controls to allow us
  256. to turn them on/off for each node.
  257. While we're at it let's also add another helper called the <a href="/docs/#api/en/helpers/GridHelper"><code class="notranslate" translate="no">GridHelper</code></a>. It
  258. makes a 2D grid on the X,Z plane. By default the grid is 10x10 units.</p>
  259. <p>We're also going to use <a href="https://github.com/georgealways/lil-gui">lil-gui</a> which is
  260. a UI library that is very popular with three.js projects. lil-gui takes an
  261. object and a property name on that object and based on the type of the property
  262. automatically makes a UI to manipulate that property.</p>
  263. <p>We want to make both a <a href="/docs/#api/en/helpers/GridHelper"><code class="notranslate" translate="no">GridHelper</code></a> and an <a href="/docs/#api/en/helpers/AxesHelper"><code class="notranslate" translate="no">AxesHelper</code></a> for each node. We need
  264. a label for each node so we'll get rid of the old loop and switch to calling
  265. some function to add the helpers for each node</p>
  266. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-// add an AxesHelper to each node
  267. -objects.forEach((node) =&gt; {
  268. - const axes = new THREE.AxesHelper();
  269. - axes.material.depthTest = false;
  270. - axes.renderOrder = 1;
  271. - node.add(axes);
  272. -});
  273. +function makeAxisGrid(node, label, units) {
  274. + const helper = new AxisGridHelper(node, units);
  275. + gui.add(helper, 'visible').name(label);
  276. +}
  277. +
  278. +makeAxisGrid(solarSystem, 'solarSystem', 25);
  279. +makeAxisGrid(sunMesh, 'sunMesh');
  280. +makeAxisGrid(earthOrbit, 'earthOrbit');
  281. +makeAxisGrid(earthMesh, 'earthMesh');
  282. +makeAxisGrid(moonOrbit, 'moonOrbit');
  283. +makeAxisGrid(moonMesh, 'moonMesh');
  284. </pre>
  285. <p><code class="notranslate" translate="no">makeAxisGrid</code> makes an <code class="notranslate" translate="no">AxisGridHelper</code> which is a class we'll create
  286. to make lil-gui happy. Like it says above lil-gui
  287. will automagically make a UI that manipulates the named property
  288. of some object. It will create a different UI depending on the type
  289. of property. We want it to create a checkbox so we need to specify
  290. a <code class="notranslate" translate="no">bool</code> property. But, we want both the axes and the grid
  291. to appear/disappear based on a single property so we'll make a class
  292. that has a getter and setter for a property. That way we can let lil-gui
  293. think it's manipulating a single property but internally we can set
  294. the visible property of both the <a href="/docs/#api/en/helpers/AxesHelper"><code class="notranslate" translate="no">AxesHelper</code></a> and <a href="/docs/#api/en/helpers/GridHelper"><code class="notranslate" translate="no">GridHelper</code></a> for a node.</p>
  295. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// Turns both axes and grid visible on/off
  296. // lil-gui requires a property that returns a bool
  297. // to decide to make a checkbox so we make a setter
  298. // and getter for `visible` which we can tell lil-gui
  299. // to look at.
  300. class AxisGridHelper {
  301. constructor(node, units = 10) {
  302. const axes = new THREE.AxesHelper();
  303. axes.material.depthTest = false;
  304. axes.renderOrder = 2; // after the grid
  305. node.add(axes);
  306. const grid = new THREE.GridHelper(units, units);
  307. grid.material.depthTest = false;
  308. grid.renderOrder = 1;
  309. node.add(grid);
  310. this.grid = grid;
  311. this.axes = axes;
  312. this.visible = false;
  313. }
  314. get visible() {
  315. return this._visible;
  316. }
  317. set visible(v) {
  318. this._visible = v;
  319. this.grid.visible = v;
  320. this.axes.visible = v;
  321. }
  322. }
  323. </pre>
  324. <p>One thing to notice is we set the <code class="notranslate" translate="no">renderOrder</code> of the <a href="/docs/#api/en/helpers/AxesHelper"><code class="notranslate" translate="no">AxesHelper</code></a>
  325. to 2 and for the <a href="/docs/#api/en/helpers/GridHelper"><code class="notranslate" translate="no">GridHelper</code></a> to 1 so that the axes get drawn after the grid.
  326. Otherwise the grid might overwrite the axes.</p>
  327. <p></p><div translate="no" class="threejs_example_container notranslate">
  328. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-sun-earth-moon-axes-grids.html"></iframe></div>
  329. <a class="threejs_center" href="/manual/examples/scenegraph-sun-earth-moon-axes-grids.html" target="_blank">click here to open in a separate window</a>
  330. </div>
  331. <p></p>
  332. <p>Turn on the <code class="notranslate" translate="no">solarSystem</code> and you'll see how the earth is exactly 10
  333. units out from the center just like we set above. You can see how the
  334. earth is in the <em>local space</em> of the <code class="notranslate" translate="no">solarSystem</code>. Similarly if you
  335. turn on the <code class="notranslate" translate="no">earthOrbit</code> you'll see how the moon is exactly 2 units
  336. from the center of the <em>local space</em> of the <code class="notranslate" translate="no">earthOrbit</code>.</p>
  337. <p>A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this</p>
  338. <p><img src="../resources/images/scenegraph-car.svg" align="center"></p>
  339. <p>If you move the car's body all the wheels will move with it. If you wanted the body
  340. to bounce separate from the wheels you might parent the body and the wheels to a "frame" node
  341. that represents the car's frame.</p>
  342. <p>Another example is a human in a game world.</p>
  343. <p><img src="../resources/images/scenegraph-human.svg" align="center"></p>
  344. <p>You can see the scene graph gets pretty complex for a human. In fact
  345. that scene graph above is simplified. For example you might extend it
  346. to cover every finger (at least another 28 nodes) and every toe
  347. (yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more.</p>
  348. <p>Let's make one semi-complex scene graph. We'll make a tank. The tank will have
  349. 6 wheels and a turret. The tank will follow a path. There will be a sphere that
  350. moves around and the tank will target the sphere.</p>
  351. <p>Here's the scene graph. The meshes are colored in green, the <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>s in blue,
  352. the lights in gold, and the cameras in purple. One camera has not been added
  353. to the scene graph.</p>
  354. <div class="threejs_center"><img src="../resources/images/scenegraph-tank.svg" style="width: 800px;"></div>
  355. <p>Look in the code to see the setup of all of these nodes.</p>
  356. <p>For the target, the thing the tank is aiming at, there is a <code class="notranslate" translate="no">targetOrbit</code>
  357. (<a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>) which just rotates similar to the <code class="notranslate" translate="no">earthOrbit</code> above. A
  358. <code class="notranslate" translate="no">targetElevation</code> (<a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>) which is a child of the <code class="notranslate" translate="no">targetOrbit</code> provides an
  359. offset from the <code class="notranslate" translate="no">targetOrbit</code> and a base elevation. Childed to that is another
  360. <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> called <code class="notranslate" translate="no">targetBob</code> which just bobs up and down relative to the
  361. <code class="notranslate" translate="no">targetElevation</code>. Finally there's the <code class="notranslate" translate="no">targetMesh</code> which is just a cube we
  362. rotate and change its colors</p>
  363. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// move target
  364. targetOrbit.rotation.y = time * .27;
  365. targetBob.position.y = Math.sin(time * 2) * 4;
  366. targetMesh.rotation.x = time * 7;
  367. targetMesh.rotation.y = time * 13;
  368. targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25);
  369. targetMaterial.color.setHSL(time * 10 % 1, 1, .25);
  370. </pre>
  371. <p>For the tank there's an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> called <code class="notranslate" translate="no">tank</code> which is used to move everything
  372. below it around. The code uses a <a href="/docs/#api/en/extras/curves/SplineCurve"><code class="notranslate" translate="no">SplineCurve</code></a> which it can ask for positions
  373. along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It
  374. asks for the current position where it puts the tank. It then asks for a
  375. position slightly further down the curve and uses that to point the tank in that
  376. direction using <a href="/docs/#api/en/core/Object3D.lookAt"><code class="notranslate" translate="no">Object3D.lookAt</code></a>.</p>
  377. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const tankPosition = new THREE.Vector2();
  378. const tankTarget = new THREE.Vector2();
  379. ...
  380. // move tank
  381. const tankTime = time * .05;
  382. curve.getPointAt(tankTime % 1, tankPosition);
  383. curve.getPointAt((tankTime + 0.01) % 1, tankTarget);
  384. tank.position.set(tankPosition.x, 0, tankPosition.y);
  385. tank.lookAt(tankTarget.x, 0, tankTarget.y);
  386. </pre>
  387. <p>The turret on top of the tank is moved automatically by being a child
  388. of the tank. To point it at the target we just ask for the target's world position
  389. and then again use <a href="/docs/#api/en/core/Object3D.lookAt"><code class="notranslate" translate="no">Object3D.lookAt</code></a></p>
  390. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const targetPosition = new THREE.Vector3();
  391. ...
  392. // face turret at target
  393. targetMesh.getWorldPosition(targetPosition);
  394. turretPivot.lookAt(targetPosition);
  395. </pre>
  396. <p>There's a <code class="notranslate" translate="no">turretCamera</code> which is a child of the <code class="notranslate" translate="no">turretMesh</code> so
  397. it will move up and down and rotate with the turret. We make that
  398. aim at the target.</p>
  399. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// make the turretCamera look at target
  400. turretCamera.lookAt(targetPosition);
  401. </pre>
  402. <p>There is also a <code class="notranslate" translate="no">targetCameraPivot</code> which is a child of <code class="notranslate" translate="no">targetBob</code> so it floats
  403. around with the target. We aim that back at the tank. Its purpose is to allow the
  404. <code class="notranslate" translate="no">targetCamera</code> to be offset from the target itself. If we instead made the camera
  405. a child of <code class="notranslate" translate="no">targetBob</code> and just aimed the camera itself it would be inside the
  406. target.</p>
  407. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// make the targetCameraPivot look at the tank
  408. tank.getWorldPosition(targetPosition);
  409. targetCameraPivot.lookAt(targetPosition);
  410. </pre>
  411. <p>Finally we rotate all the wheels</p>
  412. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">wheelMeshes.forEach((obj) =&gt; {
  413. obj.rotation.x = time * 3;
  414. });
  415. </pre>
  416. <p>For the cameras we setup an array of all 4 cameras at init time with descriptions.</p>
  417. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cameras = [
  418. { cam: camera, desc: 'detached camera', },
  419. { cam: turretCamera, desc: 'on turret looking at target', },
  420. { cam: targetCamera, desc: 'near target looking at tank', },
  421. { cam: tankCamera, desc: 'above back of tank', },
  422. ];
  423. const infoElem = document.querySelector('#info');
  424. </pre>
  425. <p>and cycle through our cameras at render time.</p>
  426. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const camera = cameras[time * .25 % cameras.length | 0];
  427. infoElem.textContent = camera.desc;
  428. </pre>
  429. <p></p><div translate="no" class="threejs_example_container notranslate">
  430. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/scenegraph-tank.html"></iframe></div>
  431. <a class="threejs_center" href="/manual/examples/scenegraph-tank.html" target="_blank">click here to open in a separate window</a>
  432. </div>
  433. <p></p>
  434. <p>I hope this gives some idea of how scene graphs work and how you might use them.
  435. Making <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> nodes and parenting things to them is an important step to using
  436. a 3D engine like three.js well. Often it might seem like some complex math is necessary
  437. to make something move and rotate the way you want. For example without a scene graph
  438. computing the motion of the moon or where to put the wheels of the car relative to its
  439. body would be very complicated but using a scene graph it becomes much easier.</p>
  440. <p><a href="materials.html">Next up we'll go over materials</a>.</p>
  441. </div>
  442. </div>
  443. </div>
  444. <script src="../resources/prettify.js"></script>
  445. <script src="../resources/lesson.js"></script>
  446. </body></html>