hello_picking.html 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Asciidoctor 1.5.4"><meta name="keywords" content="beginner, documentation, intro, node, ray, click, collision, keyinput, input"><title>jMonkeyEngine 3 Tutorial (8) - Hello Picking</title><link rel="stylesheet" href="./asciidoctor.css">
  2. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
  3. <link rel="stylesheet" href="./coderay-asciidoctor.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.css"><link rel="stylesheet" href="/home/travis/build/jMonkeyEngine/wiki/build/asciidoc/html5/jme3/beginner/twemoji-awesome.css"></head><body class="article toc2 toc-left"><div id="header"><div id="toolbar"><a href="https://github.com/jMonkeyEngine/wiki/edit/master/src/docs/asciidoc/jme3/beginner/hello_picking.adoc"><i class="fa fa-pencil-square" aria-hidden="true"></i></a><a href="https://github.com/jMonkeyEngine/wiki/new/master/src/docs/asciidoc/jme3/beginner/"><i class="fa fa-plus-square" aria-hidden="true"></i></a><input dir="auto" style="position: relative; vertical-align: top;" spellcheck="false" autocomplete="off" class="searchbox__input aa-input" id="doc-search" name="search" placeholder="Search in the doc" required="required" type="search"></div><h1>jMonkeyEngine 3 Tutorial (8) - Hello Picking</h1><div class="details"><span class="author" id="author"></span><br><span id="revnumber">version ,</span> <span id="revdate">2016/03/17 20:48</span></div><div id="toc" class="toc2"><div id="toctitle">Table of Contents</div><ul class="sectlevel1"><li><a href="#sample-code">Sample Code</a></li><li><a href="#understanding-the-helper-methods">Understanding the Helper Methods</a></li><li><a href="#understanding-ray-casting-for-hit-testing">Understanding Ray Casting for Hit Testing</a></li><li><a href="#implementing-hit-testing">Implementing Hit Testing</a><ul class="sectlevel2"><li><a href="#loading-the-scene">Loading the scene</a></li><li><a href="#setting-up-the-input-listener">Setting Up the Input Listener</a></li><li><a href="#picking-action-using-crosshairs">Picking Action Using Crosshairs</a></li><li><a href="#picking-action-using-mouse-pointer">Picking Action Using Mouse Pointer</a></li></ul></li><li><a href="#exercises">Exercises</a><ul class="sectlevel2"><li><a href="#exercise-1-magic-spell">Exercise 1: Magic Spell</a></li><li><a href="#exercise-2-shoot-a-character">Exercise 2: Shoot a Character</a></li><li><a href="#exercise-3-pick-up-into-inventory">Exercise 3: Pick up into Inventory</a></li></ul></li><li><a href="#conclusion">Conclusion</a></li></ul></div></div><div id="content"><div id="preamble"><div class="sectionbody"><div class="paragraph"><p>Previous: <a href="../../jme3/beginner/hello_animation.html">Hello Animation</a>,
  4. Next: <a href="../../jme3/beginner/hello_collision.html">Hello Collision</a></p></div>
  5. <div class="paragraph"><p>Typical interactions in games include shooting, picking up objects, and opening doors. From an implementation point of view, these apparently different interactions are surprisingly similar: The user first aims and selects a target in the 3D scene, and then triggers an action on it. We call this process picking.</p></div>
  6. <div class="paragraph"><p>You can pick something by either pressing a key on the keyboard, or by clicking with the mouse. In either case, you identify the target by aiming a ray –a straight line– into the scene. This method to implement picking is called <em>ray casting</em> (which is not the same as <em>ray tracing</em>).</p></div>
  7. <div class="paragraph"><p>This tutorial relies on what you have learned in the <a href="../../jme3/beginner/hello_input_system.html">Hello Input</a> tutorial. You find more related code samples under <a href="../../jme3/advanced/mouse_picking.html">Mouse Picking</a> and <a href="../../jme3/advanced/collision_and_intersection.html">Collision and Intersection</a>.</p></div>
  8. <div style="text-align: center;" class="imageblock"><div class="content"><img src="../../jme3/beginner/beginner-picking.png" alt="beginner-picking.png" width="" height=""></div></div></div></div>
  9. <div class="sect1"><h2 id="sample-code">Sample Code</h2><div class="sectionbody"><div class="listingblock"><div class="content"><pre class="CodeRay highlight"><code data-lang="java"><span class="keyword">package</span> <span class="namespace">jme3test.helloworld</span>;
  10. <span class="keyword">import</span> <span class="include">com.jme3.app.SimpleApplication</span>;
  11. <span class="keyword">import</span> <span class="include">com.jme3.collision.CollisionResult</span>;
  12. <span class="keyword">import</span> <span class="include">com.jme3.collision.CollisionResults</span>;
  13. <span class="keyword">import</span> <span class="include">com.jme3.font.BitmapText</span>;
  14. <span class="keyword">import</span> <span class="include">com.jme3.input.KeyInput</span>;
  15. <span class="keyword">import</span> <span class="include">com.jme3.input.MouseInput</span>;
  16. <span class="keyword">import</span> <span class="include">com.jme3.input.controls.ActionListener</span>;
  17. <span class="keyword">import</span> <span class="include">com.jme3.input.controls.KeyTrigger</span>;
  18. <span class="keyword">import</span> <span class="include">com.jme3.input.controls.MouseButtonTrigger</span>;
  19. <span class="keyword">import</span> <span class="include">com.jme3.light.DirectionalLight</span>;
  20. <span class="keyword">import</span> <span class="include">com.jme3.material.Material</span>;
  21. <span class="keyword">import</span> <span class="include">com.jme3.math.ColorRGBA</span>;
  22. <span class="keyword">import</span> <span class="include">com.jme3.math.Ray</span>;
  23. <span class="keyword">import</span> <span class="include">com.jme3.math.Vector3f</span>;
  24. <span class="keyword">import</span> <span class="include">com.jme3.scene.Geometry</span>;
  25. <span class="keyword">import</span> <span class="include">com.jme3.scene.Node</span>;
  26. <span class="keyword">import</span> <span class="include">com.jme3.scene.Spatial</span>;
  27. <span class="keyword">import</span> <span class="include">com.jme3.scene.shape.Box</span>;
  28. <span class="keyword">import</span> <span class="include">com.jme3.scene.shape.Sphere</span>;
  29. <span class="comment">/** Sample 8 - how to let the user pick (select) objects in the scene
  30. * using the mouse or key presses. Can be used for shooting, opening doors, etc. */</span>
  31. <span class="directive">public</span> <span class="type">class</span> <span class="class">HelloPicking</span> <span class="directive">extends</span> SimpleApplication {
  32. <span class="directive">public</span> <span class="directive">static</span> <span class="type">void</span> main(<span class="predefined-type">String</span><span class="type">[]</span> args) {
  33. HelloPicking app = <span class="keyword">new</span> HelloPicking();
  34. app.start();
  35. }
  36. <span class="directive">private</span> Node shootables;
  37. <span class="directive">private</span> Geometry mark;
  38. <span class="annotation">@Override</span>
  39. <span class="directive">public</span> <span class="type">void</span> simpleInitApp() {
  40. initCrossHairs(); <span class="comment">// a &quot;+&quot; in the middle of the screen to help aiming</span>
  41. initKeys(); <span class="comment">// load custom key mappings</span>
  42. initMark(); <span class="comment">// a red sphere to mark the hit</span>
  43. <span class="comment">/** create four colored boxes and a floor to shoot at: */</span>
  44. shootables = <span class="keyword">new</span> Node(<span class="string"><span class="delimiter">&quot;</span><span class="content">Shootables</span><span class="delimiter">&quot;</span></span>);
  45. rootNode.attachChild(shootables);
  46. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">a Dragon</span><span class="delimiter">&quot;</span></span>, -<span class="float">2f</span>, <span class="float">0f</span>, <span class="float">1f</span>));
  47. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">a tin can</span><span class="delimiter">&quot;</span></span>, <span class="float">1f</span>, -<span class="float">2f</span>, <span class="float">0f</span>));
  48. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">the Sheriff</span><span class="delimiter">&quot;</span></span>, <span class="float">0f</span>, <span class="float">1f</span>, -<span class="float">2f</span>));
  49. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">the Deputy</span><span class="delimiter">&quot;</span></span>, <span class="float">1f</span>, <span class="float">0f</span>, -<span class="float">4f</span>));
  50. shootables.attachChild(makeFloor());
  51. shootables.attachChild(makeCharacter());
  52. }
  53. <span class="comment">/** Declaring the &quot;Shoot&quot; action and mapping to its triggers. */</span>
  54. <span class="directive">private</span> <span class="type">void</span> initKeys() {
  55. inputManager.addMapping(<span class="string"><span class="delimiter">&quot;</span><span class="content">Shoot</span><span class="delimiter">&quot;</span></span>,
  56. <span class="keyword">new</span> KeyTrigger(KeyInput.KEY_SPACE), <span class="comment">// trigger 1: spacebar</span>
  57. <span class="keyword">new</span> MouseButtonTrigger(MouseInput.BUTTON_LEFT)); <span class="comment">// trigger 2: left-button click</span>
  58. inputManager.addListener(actionListener, <span class="string"><span class="delimiter">&quot;</span><span class="content">Shoot</span><span class="delimiter">&quot;</span></span>);
  59. }
  60. <span class="comment">/** Defining the &quot;Shoot&quot; action: Determine what was hit and how to respond. */</span>
  61. <span class="directive">private</span> <span class="predefined-type">ActionListener</span> actionListener = <span class="keyword">new</span> <span class="predefined-type">ActionListener</span>() {
  62. <span class="directive">public</span> <span class="type">void</span> onAction(<span class="predefined-type">String</span> name, <span class="type">boolean</span> keyPressed, <span class="type">float</span> tpf) {
  63. <span class="keyword">if</span> (name.equals(<span class="string"><span class="delimiter">&quot;</span><span class="content">Shoot</span><span class="delimiter">&quot;</span></span>) &amp;&amp; !keyPressed) {
  64. <span class="comment">// 1. Reset results list.</span>
  65. CollisionResults results = <span class="keyword">new</span> CollisionResults();
  66. <span class="comment">// 2. Aim the ray from cam loc to cam direction.</span>
  67. Ray ray = <span class="keyword">new</span> Ray(cam.getLocation(), cam.getDirection());
  68. <span class="comment">// 3. Collect intersections between Ray and Shootables in results list.</span>
  69. <span class="comment">// DO NOT check collision with the root node, or else ALL collisions will hit the</span>
  70. <span class="comment">// skybox! Always make a separate node for objects you want to collide with.</span>
  71. shootables.collideWith(ray, results);
  72. <span class="comment">// 4. Print the results</span>
  73. <span class="predefined-type">System</span>.out.println(<span class="string"><span class="delimiter">&quot;</span><span class="content">----- Collisions? </span><span class="delimiter">&quot;</span></span> + results.size() + <span class="string"><span class="delimiter">&quot;</span><span class="content">-----</span><span class="delimiter">&quot;</span></span>);
  74. <span class="keyword">for</span> (<span class="type">int</span> i = <span class="integer">0</span>; i &lt; results.size(); i++) {
  75. <span class="comment">// For each hit, we know distance, impact point, name of geometry.</span>
  76. <span class="type">float</span> dist = results.getCollision(i).getDistance();
  77. Vector3f pt = results.getCollision(i).getContactPoint();
  78. <span class="predefined-type">String</span> hit = results.getCollision(i).getGeometry().getName();
  79. <span class="predefined-type">System</span>.out.println(<span class="string"><span class="delimiter">&quot;</span><span class="content">* Collision #</span><span class="delimiter">&quot;</span></span> + i);
  80. <span class="predefined-type">System</span>.out.println(<span class="string"><span class="delimiter">&quot;</span><span class="content"> You shot </span><span class="delimiter">&quot;</span></span> + hit + <span class="string"><span class="delimiter">&quot;</span><span class="content"> at </span><span class="delimiter">&quot;</span></span> + pt + <span class="string"><span class="delimiter">&quot;</span><span class="content">, </span><span class="delimiter">&quot;</span></span> + dist + <span class="string"><span class="delimiter">&quot;</span><span class="content"> wu away.</span><span class="delimiter">&quot;</span></span>);
  81. }
  82. <span class="comment">// 5. Use the results (we mark the hit object)</span>
  83. <span class="keyword">if</span> (results.size() &gt; <span class="integer">0</span>) {
  84. <span class="comment">// The closest collision point is what was truly hit:</span>
  85. CollisionResult closest = results.getClosestCollision();
  86. <span class="comment">// Let's interact - we mark the hit with a red dot.</span>
  87. mark.setLocalTranslation(closest.getContactPoint());
  88. rootNode.attachChild(mark);
  89. } <span class="keyword">else</span> {
  90. <span class="comment">// No hits? Then remove the red mark.</span>
  91. rootNode.detachChild(mark);
  92. }
  93. }
  94. }
  95. };
  96. <span class="comment">/** A cube object for target practice */</span>
  97. <span class="directive">protected</span> Geometry makeCube(<span class="predefined-type">String</span> name, <span class="type">float</span> x, <span class="type">float</span> y, <span class="type">float</span> z) {
  98. <span class="predefined-type">Box</span> box = <span class="keyword">new</span> <span class="predefined-type">Box</span>(<span class="integer">1</span>, <span class="integer">1</span>, <span class="integer">1</span>);
  99. Geometry cube = <span class="keyword">new</span> Geometry(name, box);
  100. cube.setLocalTranslation(x, y, z);
  101. Material mat1 = <span class="keyword">new</span> Material(assetManager, <span class="string"><span class="delimiter">&quot;</span><span class="content">Common/MatDefs/Misc/Unshaded.j3md</span><span class="delimiter">&quot;</span></span>);
  102. mat1.setColor(<span class="string"><span class="delimiter">&quot;</span><span class="content">Color</span><span class="delimiter">&quot;</span></span>, ColorRGBA.randomColor());
  103. cube.setMaterial(mat1);
  104. <span class="keyword">return</span> cube;
  105. }
  106. <span class="comment">/** A floor to show that the &quot;shot&quot; can go through several objects. */</span>
  107. <span class="directive">protected</span> Geometry makeFloor() {
  108. <span class="predefined-type">Box</span> box = <span class="keyword">new</span> <span class="predefined-type">Box</span>(<span class="integer">15</span>, <span class="float">.2f</span>, <span class="integer">15</span>);
  109. Geometry floor = <span class="keyword">new</span> Geometry(<span class="string"><span class="delimiter">&quot;</span><span class="content">the Floor</span><span class="delimiter">&quot;</span></span>, box);
  110. floor.setLocalTranslation(<span class="integer">0</span>, -<span class="integer">4</span>, -<span class="integer">5</span>);
  111. Material mat1 = <span class="keyword">new</span> Material(assetManager, <span class="string"><span class="delimiter">&quot;</span><span class="content">Common/MatDefs/Misc/Unshaded.j3md</span><span class="delimiter">&quot;</span></span>);
  112. mat1.setColor(<span class="string"><span class="delimiter">&quot;</span><span class="content">Color</span><span class="delimiter">&quot;</span></span>, ColorRGBA.Gray);
  113. floor.setMaterial(mat1);
  114. <span class="keyword">return</span> floor;
  115. }
  116. <span class="comment">/** A red ball that marks the last spot that was &quot;hit&quot; by the &quot;shot&quot;. */</span>
  117. <span class="directive">protected</span> <span class="type">void</span> initMark() {
  118. Sphere sphere = <span class="keyword">new</span> Sphere(<span class="integer">30</span>, <span class="integer">30</span>, <span class="float">0.2f</span>);
  119. mark = <span class="keyword">new</span> Geometry(<span class="string"><span class="delimiter">&quot;</span><span class="content">BOOM!</span><span class="delimiter">&quot;</span></span>, sphere);
  120. Material mark_mat = <span class="keyword">new</span> Material(assetManager, <span class="string"><span class="delimiter">&quot;</span><span class="content">Common/MatDefs/Misc/Unshaded.j3md</span><span class="delimiter">&quot;</span></span>);
  121. mark_mat.setColor(<span class="string"><span class="delimiter">&quot;</span><span class="content">Color</span><span class="delimiter">&quot;</span></span>, ColorRGBA.Red);
  122. mark.setMaterial(mark_mat);
  123. }
  124. <span class="comment">/** A centred plus sign to help the player aim. */</span>
  125. <span class="directive">protected</span> <span class="type">void</span> initCrossHairs() {
  126. setDisplayStatView(<span class="predefined-constant">false</span>);
  127. guiFont = assetManager.loadFont(<span class="string"><span class="delimiter">&quot;</span><span class="content">Interface/Fonts/Default.fnt</span><span class="delimiter">&quot;</span></span>);
  128. BitmapText ch = <span class="keyword">new</span> BitmapText(guiFont, <span class="predefined-constant">false</span>);
  129. ch.setSize(guiFont.getCharSet().getRenderedSize() * <span class="integer">2</span>);
  130. ch.setText(<span class="string"><span class="delimiter">&quot;</span><span class="content">+</span><span class="delimiter">&quot;</span></span>); <span class="comment">// crosshairs</span>
  131. ch.setLocalTranslation( <span class="comment">// center</span>
  132. settings.getWidth() / <span class="integer">2</span> - ch.getLineWidth()/<span class="integer">2</span>,
  133. settings.getHeight() / <span class="integer">2</span> + ch.getLineHeight()/<span class="integer">2</span>, <span class="integer">0</span>);
  134. guiNode.attachChild(ch);
  135. }
  136. <span class="directive">protected</span> Spatial makeCharacter() {
  137. <span class="comment">// load a character from jme3test-test-data</span>
  138. Spatial golem = assetManager.loadModel(<span class="string"><span class="delimiter">&quot;</span><span class="content">Models/Oto/Oto.mesh.xml</span><span class="delimiter">&quot;</span></span>);
  139. golem.scale(<span class="float">0.5f</span>);
  140. golem.setLocalTranslation(-<span class="float">1.0f</span>, -<span class="float">1.5f</span>, -<span class="float">0.6f</span>);
  141. <span class="comment">// We must add a light to make the model visible</span>
  142. DirectionalLight sun = <span class="keyword">new</span> DirectionalLight();
  143. sun.setDirection(<span class="keyword">new</span> Vector3f(-<span class="float">0.1f</span>, -<span class="float">0.7f</span>, -<span class="float">1.0f</span>));
  144. golem.addLight(sun);
  145. <span class="keyword">return</span> golem;
  146. }
  147. }</code></pre></div></div>
  148. <div class="paragraph"><p>You should see four colored cubes floating over a gray floor, and cross-hairs. Aim the cross-hairs and click, or press the spacebar to shoot. The hit spot is marked with a red dot.</p></div>
  149. <div class="paragraph"><p>Keep an eye on the application&#8217;s output stream, it will give you more details: The name of the mesh that was hit, the coordinates of the hit, and the distance.</p></div></div></div>
  150. <div class="sect1"><h2 id="understanding-the-helper-methods">Understanding the Helper Methods</h2><div class="sectionbody"><div class="paragraph"><p>The methods <code>makeCube()</code>, <code>makeFloor()</code>, <code>initMark()</code>, and <code>initCrossHairs</code>, are custom helper methods. We call them from <code>simpleInitApp()</code> to initialize the scenegraph with sample content.</p></div>
  151. <div class="olist arabic"><ol class="arabic"><li><p><code>makeCube()</code> creates simple colored boxes for “target practice.</p></li><li><p><code>makeFloor()</code> creates a gray floor node for “target practice.</p></li><li><p><code>initMark()</code> creates a red sphere (“mark). We will use it later to mark the spot that was hit.</p><div class="ulist"><ul><li><p>Note that the mark is not attached and therefor not visible at the start!</p></li></ul></div></li><li><p><code>initCrossHairs()</code> creates simple cross-hairs by printing a “+ sign in the middle of the screen.</p><div class="ulist"><ul><li><p>Note that the cross-hairs are attached to the <code>guiNode</code>, not to the <code>rootNode</code>.</p></li></ul></div></li></ol></div>
  152. <div class="paragraph"><p>In this example, we attached all “shootable objects to one custom node, <code>Shootables</code>. This is an optimization so the engine only has to calculate intersections with objects we are actually interested in. The <code>Shootables</code> node is attached to the <code>rootNode</code> as usual.</p></div></div></div>
  153. <div class="sect1"><h2 id="understanding-ray-casting-for-hit-testing">Understanding Ray Casting for Hit Testing</h2><div class="sectionbody"><div class="paragraph"><p>Our goal is to determine which box the user “shot (picked). In general, we want to determine which mesh the user has selected by aiming the cross-hairs at it. Mathematically, we draw a line from the camera and see whether it intersects with objects in the 3D scene. This line is called a ray.</p></div>
  154. <div class="paragraph"><p>Here is our simple ray casting algorithm for picking objects:</p></div>
  155. <div class="olist arabic"><ol class="arabic"><li><p>Reset the results list.</p></li><li><p>Cast a ray from cam location into the cam direction.</p></li><li><p>Collect all intersections between the ray and <code>Shootable</code> nodes in the <code>results</code> list.</p></li><li><p>Use the results list to determine what was hit:</p><div class="olist loweralpha"><ol class="loweralpha" type="a"><li><p>For each hit, JME reports its distance from the camera, impact point, and the name of the mesh.</p></li><li><p>Sort the results by distance.</p></li><li><p>Take the closest result, it is the mesh that was hit.</p></li></ol></div></li></ol></div></div></div>
  156. <div class="sect2"><h3 id="implementing-hit-testing">Implementing Hit Testing</h3><div class="sect2"><h3 id="loading-the-scene">Loading the scene</h3><div class="paragraph"><p>First initialize some shootable nodes and attach them to the scene. You will use the <code>mark</code> object later.</p></div>
  157. <div class="listingblock"><div class="content"><pre class="CodeRay highlight"><code data-lang="java"> Node shootables;
  158. Geometry mark;
  159. <span class="annotation">@Override</span>
  160. <span class="directive">public</span> <span class="type">void</span> simpleInitApp() {
  161. initCrossHairs();
  162. initKeys();
  163. initMark();
  164. shootables = <span class="keyword">new</span> Node(<span class="string"><span class="delimiter">&quot;</span><span class="content">Shootables</span><span class="delimiter">&quot;</span></span>);
  165. rootNode.attachChild(shootables);
  166. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">a Dragon</span><span class="delimiter">&quot;</span></span>, -<span class="float">2f</span>, <span class="float">0f</span>, <span class="float">1f</span>));
  167. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">a tin can</span><span class="delimiter">&quot;</span></span>, <span class="float">1f</span>,-<span class="float">2f</span>, <span class="float">0f</span>));
  168. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">the Sheriff</span><span class="delimiter">&quot;</span></span>, <span class="float">0f</span>, <span class="float">1f</span>,-<span class="float">2f</span>));
  169. shootables.attachChild(makeCube(<span class="string"><span class="delimiter">&quot;</span><span class="content">the Deputy</span><span class="delimiter">&quot;</span></span>, <span class="float">1f</span>, <span class="float">0f</span>, -<span class="integer">4</span>));
  170. shootables.attachChild(makeFloor());
  171. }</code></pre></div></div></div>
  172. <div class="sect2"><h3 id="setting-up-the-input-listener">Setting Up the Input Listener</h3><div class="paragraph"><p>Next you declare the shooting action. It can be triggered either by clicking, or by pressing the space bar. The <code>initKeys()</code> method is called from <code>simpleInitApp()</code> to set up these input mappings.</p></div>
  173. <div class="listingblock"><div class="content"><pre class="CodeRay highlight"><code data-lang="java"> <span class="comment">/** Declaring the &quot;Shoot&quot; action and its triggers. */</span>
  174. <span class="directive">private</span> <span class="type">void</span> initKeys() {
  175. inputManager.addMapping(<span class="string"><span class="delimiter">&quot;</span><span class="content">Shoot</span><span class="delimiter">&quot;</span></span>, <span class="comment">// Declare...</span>
  176. <span class="keyword">new</span> KeyTrigger(KeyInput.KEY_SPACE), <span class="comment">// trigger 1: spacebar, or</span>
  177. <span class="keyword">new</span> MouseButtonTrigger(MouseInput.BUTTON_LEFT)); <span class="comment">// trigger 2: left-button click</span>
  178. inputManager.addListener(actionListener, <span class="string"><span class="delimiter">&quot;</span><span class="content">Shoot</span><span class="delimiter">&quot;</span></span>); <span class="comment">// ... and add.</span>
  179. }</code></pre></div></div></div>
  180. <div class="sect2"><h3 id="picking-action-using-crosshairs">Picking Action Using Crosshairs</h3><div class="paragraph"><p>Next we implement the ActionListener that responds to the Shoot trigger with an action. The action follows the ray casting algorithm described above:</p></div>
  181. <div class="olist arabic"><ol class="arabic"><li><p>For every click or press of the spacebar, the <code>Shoot</code> action is triggered.</p></li><li><p>The action casts a ray forward and determines intersections with shootable objects (= ray casting).</p></li><li><p>For any target that has been hit, it prints name, distance, and coordinates of the hit.</p></li><li><p>Finally it attaches a red mark to the closest result, to highlight the spot that was actually hit.</p></li><li><p>When nothing was hit, the results list is empty, and the red mark is removed.</p></li></ol></div>
  182. <div class="paragraph"><p>Note how it prints a lot of output to show you which hits were registered.</p></div>
  183. <div class="listingblock"><div class="content"><pre class="CodeRay highlight"><code data-lang="java"> <span class="comment">/** Defining the &quot;Shoot&quot; action: Determine what was hit and how to respond. */</span>
  184. <span class="directive">private</span> <span class="predefined-type">ActionListener</span> actionListener = <span class="keyword">new</span> <span class="predefined-type">ActionListener</span>() {
  185. <span class="annotation">@Override</span>
  186. <span class="directive">public</span> <span class="type">void</span> onAction(<span class="predefined-type">String</span> name, <span class="type">boolean</span> keyPressed, <span class="type">float</span> tpf) {
  187. <span class="keyword">if</span> (name.equals(<span class="string"><span class="delimiter">&quot;</span><span class="content">Shoot</span><span class="delimiter">&quot;</span></span>) &amp;&amp; !keyPressed) {
  188. <span class="comment">// 1. Reset results list.</span>
  189. CollisionResults results = <span class="keyword">new</span> CollisionResults();
  190. <span class="comment">// 2. Aim the ray from cam loc to cam direction.</span>
  191. Ray ray = <span class="keyword">new</span> Ray(cam.getLocation(), cam.getDirection());
  192. <span class="comment">// 3. Collect intersections between Ray and Shootables in results list.</span>
  193. shootables.collideWith(ray, results);
  194. <span class="comment">// 4. Print results.</span>
  195. <span class="predefined-type">System</span>.out.println(<span class="string"><span class="delimiter">&quot;</span><span class="content">----- Collisions? </span><span class="delimiter">&quot;</span></span> + results.size() + <span class="string"><span class="delimiter">&quot;</span><span class="content">-----</span><span class="delimiter">&quot;</span></span>);
  196. <span class="keyword">for</span> (<span class="type">int</span> i = <span class="integer">0</span>; i &lt; results.size(); i++) {
  197. <span class="comment">// For each hit, we know distance, impact point, name of geometry.</span>
  198. <span class="type">float</span> dist = results.getCollision(i).getDistance();
  199. Vector3f pt = results.getCollision(i).getContactPoint();
  200. <span class="predefined-type">String</span> hit = results.getCollision(i).getGeometry().getName();
  201. <span class="predefined-type">System</span>.out.println(<span class="string"><span class="delimiter">&quot;</span><span class="content">* Collision #</span><span class="delimiter">&quot;</span></span> + i);
  202. <span class="predefined-type">System</span>.out.println(<span class="string"><span class="delimiter">&quot;</span><span class="content"> You shot </span><span class="delimiter">&quot;</span></span> + hit + <span class="string"><span class="delimiter">&quot;</span><span class="content"> at </span><span class="delimiter">&quot;</span></span> + pt + <span class="string"><span class="delimiter">&quot;</span><span class="content">, </span><span class="delimiter">&quot;</span></span> + dist + <span class="string"><span class="delimiter">&quot;</span><span class="content"> wu away.</span><span class="delimiter">&quot;</span></span>);
  203. }
  204. <span class="comment">// 5. Use the results (we mark the hit object)</span>
  205. <span class="keyword">if</span> (results.size() &gt; <span class="integer">0</span>){
  206. <span class="comment">// The closest collision point is what was truly hit:</span>
  207. CollisionResult closest = results.getClosestCollision();
  208. mark.setLocalTranslation(closest.getContactPoint());
  209. <span class="comment">// Let's interact - we mark the hit with a red dot.</span>
  210. rootNode.attachChild(mark);
  211. } <span class="keyword">else</span> {
  212. <span class="comment">// No hits? Then remove the red mark.</span>
  213. rootNode.detachChild(mark);
  214. }
  215. }
  216. }
  217. };</code></pre></div></div>
  218. <div class="paragraph"><p><strong>Tip:</strong> Notice how you use the provided method <code>results.getClosestCollision().getContactPoint()</code> to determine the <em>closest</em> hit&#8217;s location. If your game includes a “weapon or “spell that can hit multiple targets, you could also loop over the list of results, and interact with each of them.</p></div></div>
  219. <div class="sect2"><h3 id="picking-action-using-mouse-pointer">Picking Action Using Mouse Pointer</h3><div class="paragraph"><p>The above example assumes that the player is aiming crosshairs (attached to the center of the screen) at the target. But you can change the picking code to allow you to freely click at objects in the scene with a visible mouse pointer. In order to do this you have to convert the 2d screen coordinates of the click to 3D world coordinates to get the start point of the picking ray.</p></div>
  220. <div class="olist arabic"><ol class="arabic"><li><p>Reset result list.</p></li><li><p>Get 2D click coordinates.</p></li><li><p>Convert 2D screen coordinates to their 3D equivalent.</p></li><li><p>Aim the ray from the clicked 3D location forwards into the scene.</p></li><li><p>Collect intersections between ray and all nodes into a results list.</p></li></ol></div>
  221. <div class="listingblock"><div class="content"><pre class="CodeRay highlight"><code data-lang="java">...
  222. CollisionResults results = <span class="keyword">new</span> CollisionResults();
  223. Vector2f click2d = inputManager.getCursorPosition().clone();
  224. Vector3f click3d = cam.getWorldCoordinates(
  225. click2d, <span class="float">0f</span>).clone();
  226. Vector3f dir = cam.getWorldCoordinates(
  227. click2d, <span class="float">1f</span>).subtractLocal(click3d).normalizeLocal();
  228. Ray ray = <span class="keyword">new</span> Ray(click3d, dir);
  229. shootables.collideWith(ray, results);
  230. ...</code></pre></div></div>
  231. <div class="paragraph"><p>Use this together with <code>inputManager.setCursorVisible(true)</code> to make certain the cursor is visible.</p></div>
  232. <div class="paragraph"><p>Note that since you now use the mouse for picking, you can no longer use it to rotate the camera. If you want to have a visible mouse pointer for picking in your game, you have to redefine the camera rotation mappings.</p></div></div></div>
  233. <div class="sect2"><h3 id="exercises">Exercises</h3><div class="paragraph"><p>After a hit was registered, the closest object is identified as target, and marked with a red dot.
  234. Modify the code sample to solve these exercises:</p></div>
  235. <div class="sect2"><h3 id="exercise-1-magic-spell">Exercise 1: Magic Spell</h3><div class="paragraph"><p>Change the color of the closest clicked target!<br>
  236. Here are some tips:</p></div>
  237. <div class="olist arabic"><ol class="arabic"><li><p>Go to the line where the closest target is indentified, and add your changes after that.</p></li><li><p>To change an object&#8217;s color, you must first know its Geometry. Identify the node by identifying the target&#8217;s name.</p><div class="ulist"><ul><li><p>Use <code>Geometry g = closest.getGeometry();</code></p></li></ul></div></li><li><p>Create a new color material and set the node&#8217;s Material to this color.</p><div class="ulist"><ul><li><p>Look inside the <code>makeCube()</code> method for an example of how to set random colors.</p></li></ul></div></li></ol></div></div>
  238. <div class="sect2"><h3 id="exercise-2-shoot-a-character">Exercise 2: Shoot a Character</h3><div class="paragraph"><p>Shooting boxes isn&#8217;t very exciting – can you add code that loads and positions a model in the scene, and shoot at it?</p></div>
  239. <div class="ulist"><ul><li><p>Tip: You can use <code>Spatial golem = assetManager.loadModel(“Models/Oto/Oto.mesh.xml);</code> from the engine&#8217;s jme3-test-data.jar.</p></li><li><p>Tip: Models are shaded! You need some light!</p></li></ul></div></div>
  240. <div class="sect2"><h3 id="exercise-3-pick-up-into-inventory">Exercise 3: Pick up into Inventory</h3><div class="paragraph"><p>Change the code as follows to simulate the player picking up objects into the inventory: When you click once, the closest target is identified and detached from the scene. When you click a second time, the target is reattached at the location that you have clicked. Here are some tips:</p></div>
  241. <div class="olist arabic"><ol class="arabic"><li><p>Create an inventory node to store the detached nodes temporarily.</p></li><li><p>The inventory node is not attached to the rootNode.</p></li><li><p>You can make the inventory visible by attaching the inventory node to the guiNode (which attaches it to the HUD). Note the following caveats:</p><div class="ulist"><ul><li><p>If your nodes use a lit Material (not “Unshaded.j3md), also add a light to the guiNode.</p></li><li><p>Size units are pixels in the HUD, therefor a 2-wu cube is displayed only 2 pixels wide in the HUD. – Scale it bigger!</p></li><li><p>Position the nodes: The bottom left corner of the HUD is (0f,0f), and the top right corner is at (settings.getWidth(),settings.getHeight()).</p></li></ul></div></li></ol></div>
  242. <div class="admonitionblock important"><table><tr><td class="icon"><i class="fa icon-important" title="Important"></i></td><td class="content"><div class="paragraph"><p>Link to user-proposed solutions: <a href="../../jme3/beginner/solutions.html">jme3:solutions</a><br>
  243. <u>Be sure to try to solve them for yourself first!</u></p></div></td></tr></table></div></div></div>
  244. <div class="sect1"><h2 id="conclusion">Conclusion</h2><div class="sectionbody"><div class="paragraph"><p>You have learned how to use ray casting to solve the task of determining what object a user selected on the screen. You learned that this can be used for a variety of interactions, such as shooting, opening, picking up and dropping items, pressing a button or lever, etc.</p></div>
  245. <div class="paragraph"><p>Use your imagination from here:</p></div>
  246. <div class="ulist"><ul><li><p>In your game, the click can trigger any action on the identified Geometry: Detach it and put it into the inventory, attach something to it, trigger an animation or effect, open a door or crate, – etc.</p></li><li><p>In your game, you could replace the red mark with a particle emitter, add an explosion effect, play a sound, calculate the new score after each hit depending on what was hit – etc.</p></li></ul></div>
  247. <div class="paragraph"><p>Now, wouldn&#8217;t it be nice if those targets and the floor were solid objects and you could walk around between them? Let&#8217;s continue to learn about <a href="../../jme3/beginner/hello_collision.html">Collision Detection</a>.</p></div>
  248. <hr>
  249. <div class="paragraph"><p>See also:</p></div>
  250. <div class="ulist"><ul><li><p><a href="../../jme3/beginner/hello_input_system.html">Hello Input</a></p></li><li><p><a href="../../jme3/advanced/mouse_picking.html">Mouse Picking</a></p></li><li><p><a href="../../jme3/advanced/collision_and_intersection.html">Collision and Intersection</a></p></li></ul></div></div></div></div><div id="footer"><div id="footer-text">Version <br>Last updated 2020-04-29 14:53:30 +00:00</div></div><script type="text/javascript" src="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.js"></script><script>docsearch({
  251. apiKey: 'a736b6d93de805e26ec2f49b55013fbd',
  252. indexName: 'jmonkeyengine',
  253. inputSelector: '#doc-search',
  254. debug: false // Set debug to true if you want to inspect the dropdown
  255. });</script></body></html>