hello_picking.adoc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. = jMonkeyEngine 3 Tutorial (8) - Hello Picking
  2. :author:
  3. :revnumber:
  4. :revdate: 2020/07/06
  5. :keywords: beginner, documentation, intro, node, ray, click, collision, keyinput, input
  6. 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.
  7. 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 _ray casting_ (which is not the same as _ray tracing_).
  8. This tutorial relies on what you have learned in the xref:beginner/hello_input_system.adoc[Hello Input] tutorial. You find more related code samples under xref:core:input/mouse_picking.adoc[Mouse Picking] and xref:core:collision/collision_and_intersection.adoc[Collision and Intersection].
  9. image::beginner/beginner-picking.png[beginner-picking.png,width="",height="",align="center"]
  10. == Sample Code
  11. [source,java]
  12. ----
  13. package jme3test.helloworld;
  14. import com.jme3.app.SimpleApplication;
  15. import com.jme3.collision.CollisionResult;
  16. import com.jme3.collision.CollisionResults;
  17. import com.jme3.font.BitmapText;
  18. import com.jme3.input.KeyInput;
  19. import com.jme3.input.MouseInput;
  20. import com.jme3.input.controls.ActionListener;
  21. import com.jme3.input.controls.KeyTrigger;
  22. import com.jme3.input.controls.MouseButtonTrigger;
  23. import com.jme3.light.DirectionalLight;
  24. import com.jme3.material.Material;
  25. import com.jme3.math.ColorRGBA;
  26. import com.jme3.math.Ray;
  27. import com.jme3.math.Vector3f;
  28. import com.jme3.scene.Geometry;
  29. import com.jme3.scene.Node;
  30. import com.jme3.scene.Spatial;
  31. import com.jme3.scene.shape.Box;
  32. import com.jme3.scene.shape.Sphere;
  33. /** Sample 8 - how to let the user pick (select) objects in the scene
  34. * using the mouse or key presses. Can be used for shooting, opening doors, etc. */
  35. public class HelloPicking extends SimpleApplication {
  36. public static void main(String[] args) {
  37. HelloPicking app = new HelloPicking();
  38. app.start();
  39. }
  40. private Node shootables;
  41. private Geometry mark;
  42. @Override
  43. public void simpleInitApp() {
  44. initCrossHairs(); // a "+" in the middle of the screen to help aiming
  45. initKeys(); // load custom key mappings
  46. initMark(); // a red sphere to mark the hit
  47. /** create four colored boxes and a floor to shoot at: */
  48. shootables = new Node("Shootables");
  49. rootNode.attachChild(shootables);
  50. shootables.attachChild(makeCube("a Dragon", -2f, 0f, 1f));
  51. shootables.attachChild(makeCube("a tin can", 1f, -2f, 0f));
  52. shootables.attachChild(makeCube("the Sheriff", 0f, 1f, -2f));
  53. shootables.attachChild(makeCube("the Deputy", 1f, 0f, -4f));
  54. shootables.attachChild(makeFloor());
  55. shootables.attachChild(makeCharacter());
  56. }
  57. /** Declaring the "Shoot" action and mapping to its triggers. */
  58. private void initKeys() {
  59. inputManager.addMapping("Shoot",
  60. new KeyTrigger(KeyInput.KEY_SPACE), // trigger 1: spacebar
  61. new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); // trigger 2: left-button click
  62. inputManager.addListener(actionListener, "Shoot");
  63. }
  64. /** Defining the "Shoot" action: Determine what was hit and how to respond. */
  65. final private ActionListener actionListener = new ActionListener() {
  66. @Override
  67. public void onAction(String name, boolean keyPressed, float tpf) {
  68. if (name.equals("Shoot") && !keyPressed) {
  69. // 1. Reset results list.
  70. CollisionResults results = new CollisionResults();
  71. // 2. Aim the ray from cam loc to cam direction.
  72. Ray ray = new Ray(cam.getLocation(), cam.getDirection());
  73. // 3. Collect intersections between Ray and Shootables in results list.
  74. shootables.collideWith(ray, results);
  75. // 4. Print the results
  76. System.out.println("----- Collisions? " + results.size() + "-----");
  77. for (int i = 0; i < results.size(); i++) {
  78. // For each hit, we know distance, impact point, name of geometry.
  79. float dist = results.getCollision(i).getDistance();
  80. Vector3f pt = results.getCollision(i).getContactPoint();
  81. String hit = results.getCollision(i).getGeometry().getName();
  82. System.out.println("* Collision #" + i);
  83. System.out.println(" You shot " + hit + " at " + pt + ", " + dist + " wu away.");
  84. }
  85. // 5. Use the results (we mark the hit object)
  86. if (results.size() > 0) {
  87. // The closest collision point is what was truly hit:
  88. CollisionResult closest = results.getClosestCollision();
  89. // Let's interact - we mark the hit with a red dot.
  90. mark.setLocalTranslation(closest.getContactPoint());
  91. rootNode.attachChild(mark);
  92. } else {
  93. // No hits? Then remove the red mark.
  94. rootNode.detachChild(mark);
  95. }
  96. }
  97. }
  98. };
  99. /** A cube object for target practice */
  100. private Geometry makeCube(String name, float x, float y, float z) {
  101. Box box = new Box(1, 1, 1);
  102. Geometry cube = new Geometry(name, box);
  103. cube.setLocalTranslation(x, y, z);
  104. Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
  105. mat1.setColor("Color", ColorRGBA.randomColor());
  106. cube.setMaterial(mat1);
  107. return cube;
  108. }
  109. /** A floor to show that the "shot" can go through several objects. */
  110. private Geometry makeFloor() {
  111. Box box = new Box(15, .2f, 15);
  112. Geometry floor = new Geometry("the Floor", box);
  113. floor.setLocalTranslation(0, -4, -5);
  114. Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
  115. mat1.setColor("Color", ColorRGBA.Gray);
  116. floor.setMaterial(mat1);
  117. return floor;
  118. }
  119. /** A red ball that marks the last spot that was "hit" by the "shot". */
  120. private void initMark() {
  121. Sphere sphere = new Sphere(30, 30, 0.2f);
  122. mark = new Geometry("BOOM!", sphere);
  123. Material mark_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
  124. mark_mat.setColor("Color", ColorRGBA.Red);
  125. mark.setMaterial(mark_mat);
  126. }
  127. /** A centred plus sign to help the player aim. */
  128. private void initCrossHairs() {
  129. setDisplayStatView(false);
  130. guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
  131. BitmapText ch = new BitmapText(guiFont);
  132. ch.setSize(guiFont.getCharSet().getRenderedSize() * 2);
  133. ch.setText("+"); // crosshairs
  134. ch.setLocalTranslation( // center
  135. settings.getWidth() / 2 - ch.getLineWidth()/2, settings.getHeight() / 2 + ch.getLineHeight()/2, 0);
  136. guiNode.attachChild(ch);
  137. }
  138. private Spatial makeCharacter() {
  139. // load a character from jme3test-test-data
  140. Spatial golem = assetManager.loadModel("Models/Oto/Oto.mesh.xml");
  141. golem.scale(0.5f);
  142. golem.setLocalTranslation(-1.0f, -1.5f, -0.6f);
  143. // We must add a light to make the model visible
  144. DirectionalLight sun = new DirectionalLight();
  145. sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f));
  146. golem.addLight(sun);
  147. return golem;
  148. }
  149. }
  150. ----
  151. 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.
  152. Keep an eye on the application'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.
  153. == Understanding the Helper Methods
  154. The methods `makeCube()`, `makeFloor()`, `initMark()`, and `initCrossHairs`, are custom helper methods. We call them from `simpleInitApp()` to initialize the scenegraph with sample content.
  155. . `makeCube()` creates simple colored boxes for "`target`" practice.
  156. . `makeFloor()` creates a gray floor node for "`target`" practice.
  157. . `initMark()` creates a red sphere (mark). We will use it later to mark the spot that was hit.
  158. ** Note that the mark is not attached and therefor not visible at the start!
  159. . `initCrossHairs()` creates simple cross-hairs by printing a "`+`" sign in the middle of the screen.
  160. ** Note that the cross-hairs are attached to the `guiNode`, not to the `rootNode`.
  161. In this example, we attached all "`shootable`" objects to one custom node, `Shootables`. This is an optimization so the engine only has to calculate intersections with objects we are actually interested in. The `Shootables` node is attached to the `rootNode` as usual.
  162. == Understanding Ray Casting for Hit Testing
  163. 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.
  164. Here is our simple ray casting algorithm for picking objects:
  165. . Reset the results list.
  166. . Cast a ray from cam location into the cam direction.
  167. . Collect all intersections between the ray and `Shootable` nodes in the `results` list.
  168. . Use the results list to determine what was hit:
  169. .. For each hit, JME reports its distance from the camera, impact point, and the name of the mesh.
  170. .. Sort the results by distance.
  171. .. Take the closest result, it is the mesh that was hit.
  172. == Implementing Hit Testing
  173. === Loading the scene
  174. First initialize some shootable nodes and attach them to the scene. You will use the `mark` object later.
  175. [source,java]
  176. ----
  177. Node shootables;
  178. Geometry mark;
  179. @Override
  180. public void simpleInitApp() {
  181. initCrossHairs();
  182. initKeys();
  183. initMark();
  184. shootables = new Node("Shootables");
  185. rootNode.attachChild(shootables);
  186. shootables.attachChild(makeCube("a Dragon", -2f, 0f, 1f));
  187. shootables.attachChild(makeCube("a tin can", 1f,-2f, 0f));
  188. shootables.attachChild(makeCube("the Sheriff", 0f, 1f,-2f));
  189. shootables.attachChild(makeCube("the Deputy", 1f, 0f, -4));
  190. shootables.attachChild(makeFloor());
  191. }
  192. ----
  193. === Setting Up the Input Listener
  194. Next you declare the shooting action. It can be triggered either by clicking, or by pressing the space bar. The `initKeys()` method is called from `simpleInitApp()` to set up these input mappings.
  195. [source,java]
  196. ----
  197. /** Declaring the "Shoot" action and its triggers. */
  198. private void initKeys() {
  199. inputManager.addMapping("Shoot", // Declare...
  200. new KeyTrigger(KeyInput.KEY_SPACE), // trigger 1: spacebar, or
  201. new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); // trigger 2: left-button click
  202. inputManager.addListener(actionListener, "Shoot"); // ... and add.
  203. }
  204. ----
  205. === Picking Action Using Crosshairs
  206. Next we implement the ActionListener that responds to the Shoot trigger with an action. The action follows the ray casting algorithm described above:
  207. . For every click or press of the spacebar, the `Shoot` action is triggered.
  208. . The action casts a ray forward and determines intersections with shootable objects (= ray casting).
  209. . For any target that has been hit, it prints name, distance, and coordinates of the hit.
  210. . Finally it attaches a red mark to the closest result, to highlight the spot that was actually hit.
  211. . When nothing was hit, the results list is empty, and the red mark is removed.
  212. Note how it prints a lot of output to show you which hits were registered.
  213. [source,java]
  214. ----
  215. /** Defining the "Shoot" action: Determine what was hit and how to respond. */
  216. final private ActionListener actionListener = new ActionListener() {
  217. @Override
  218. public void onAction(String name, boolean keyPressed, float tpf) {
  219. if (name.equals("Shoot") && !keyPressed) {
  220. // 1. Reset results list.
  221. CollisionResults results = new CollisionResults();
  222. // 2. Aim the ray from cam loc to cam direction.
  223. Ray ray = new Ray(cam.getLocation(), cam.getDirection());
  224. // 3. Collect intersections between Ray and Shootables in results list.
  225. shootables.collideWith(ray, results);
  226. // 4. Print results.
  227. System.out.println("----- Collisions? " + results.size() + "-----");
  228. for (int i = 0; i < results.size(); i++) {
  229. // For each hit, we know distance, impact point, name of geometry.
  230. float dist = results.getCollision(i).getDistance();
  231. Vector3f pt = results.getCollision(i).getContactPoint();
  232. String hit = results.getCollision(i).getGeometry().getName();
  233. System.out.println("* Collision #" + i);
  234. System.out.println(" You shot " + hit + " at " + pt + ", " + dist + " wu away.");
  235. }
  236. // 5. Use the results (we mark the hit object)
  237. if (results.size() > 0){
  238. // The closest collision point is what was truly hit:
  239. CollisionResult closest = results.getClosestCollision();
  240. mark.setLocalTranslation(closest.getContactPoint());
  241. // Let's interact - we mark the hit with a red dot.
  242. rootNode.attachChild(mark);
  243. } else {
  244. // No hits? Then remove the red mark.
  245. rootNode.detachChild(mark);
  246. }
  247. }
  248. }
  249. };
  250. ----
  251. TIP: Notice how you use the provided method `results.getClosestCollision().getContactPoint()` to determine the _closest_ hit'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.
  252. === Picking Action Using Mouse Pointer
  253. 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.
  254. . Reset result list.
  255. . Get 2D click coordinates.
  256. . Convert 2D screen coordinates to their 3D equivalent.
  257. . Aim the ray from the clicked 3D location forwards into the scene.
  258. . Collect intersections between ray and all nodes into a results list.
  259. [source,java]
  260. ----
  261. ...
  262. CollisionResults results = new CollisionResults();
  263. Vector2f click2d = inputManager.getCursorPosition().clone();
  264. Vector3f click3d = cam.getWorldCoordinates(
  265. click2d, 0f).clone();
  266. Vector3f dir = cam.getWorldCoordinates(
  267. click2d, 1f).subtractLocal(click3d).normalizeLocal();
  268. Ray ray = new Ray(click3d, dir);
  269. shootables.collideWith(ray, results);
  270. ...
  271. ----
  272. Use this together with `inputManager.setCursorVisible(true)` to make certain the cursor is visible.
  273. 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.
  274. == Exercises
  275. After a hit was registered, the closest object is identified as target, and marked with a red dot.
  276. Modify the code sample to solve these exercises:
  277. === Exercise 1: Magic Spell
  278. Change the color of the closest clicked target! +
  279. Here are some tips:
  280. . Go to the line where the closest target is identified, and add your changes after that.
  281. . To change an object's color, you must first know its Geometry. Identify the node by identifying the target's name.
  282. ** Use `Geometry g = closest.getGeometry();`
  283. . Create a new color material and set the node's Material to this color.
  284. ** Look inside the `makeCube()` method for an example of how to set random colors.
  285. === Exercise 2: Shoot a Character
  286. Shooting boxes isn't very exciting – can you add code that loads and positions a model in the scene, and shoot at it?
  287. * Tip: You can use `Spatial golem = assetManager.loadModel("Models/Oto/Oto.mesh.xml");` from the engine's jme3-test-data.jar.
  288. * Tip: Models are shaded! You need some light!
  289. === Exercise 3: Pick up into Inventory
  290. 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:
  291. . Create an inventory node to store the detached nodes temporarily.
  292. . The inventory node is not attached to the rootNode.
  293. . You can make the inventory visible by attaching the inventory node to the guiNode (which attaches it to the HUD). Note the following caveats:
  294. ** If your nodes use a lit Material (not "`Unshaded.j3md`"), also add a light to the guiNode.
  295. ** Size units are pixels in the HUD, therefor a 2-wu cube is displayed only 2 pixels wide in the HUD. – Scale it bigger!
  296. ** Position the nodes: The bottom left corner of the HUD is (0f,0f), and the top right corner is at (settings.getWidth(),settings.getHeight()).
  297. [IMPORTANT]
  298. ====
  299. <<beginner/solutions.adoc#hello-picking,Some proposed solutions>> +
  300. *Be sure to try to solve them for yourself first!*
  301. ====
  302. == Conclusion
  303. 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.
  304. Use your imagination from here:
  305. * 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.
  306. * 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.