1 /*
2  * Copyright (c) 2009-2010 jMonkeyEngine
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  * * Redistributions of source code must retain the above copyright
10  *   notice, this list of conditions and the following disclaimer.
11  *
12  * * Redistributions in binary form must reproduce the above copyright
13  *   notice, this list of conditions and the following disclaimer in the
14  *   documentation and/or other materials provided with the distribution.
15  *
16  * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
17  *   may be used to endorse or promote products derived from this software
18  *   without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 package jme3test.helloworld;
34 
35 import com.jme3.app.SimpleApplication;
36 import com.jme3.collision.CollisionResult;
37 import com.jme3.collision.CollisionResults;
38 import com.jme3.font.BitmapText;
39 import com.jme3.input.KeyInput;
40 import com.jme3.input.MouseInput;
41 import com.jme3.input.controls.ActionListener;
42 import com.jme3.input.controls.KeyTrigger;
43 import com.jme3.input.controls.MouseButtonTrigger;
44 import com.jme3.light.DirectionalLight;
45 import com.jme3.material.Material;
46 import com.jme3.math.ColorRGBA;
47 import com.jme3.math.Ray;
48 import com.jme3.math.Vector3f;
49 import com.jme3.scene.Geometry;
50 import com.jme3.scene.Node;
51 import com.jme3.scene.Spatial;
52 import com.jme3.scene.shape.Box;
53 import com.jme3.scene.shape.Sphere;
54 
55 /** Sample 8 - how to let the user pick (select) objects in the scene
56  * using the mouse or key presses. Can be used for shooting, opening doors, etc. */
57 public class HelloPicking extends SimpleApplication {
58 
main(String[] args)59   public static void main(String[] args) {
60     HelloPicking app = new HelloPicking();
61     app.start();
62   }
63   Node shootables;
64   Geometry mark;
65 
66   @Override
simpleInitApp()67   public void simpleInitApp() {
68     initCrossHairs(); // a "+" in the middle of the screen to help aiming
69     initKeys();       // load custom key mappings
70     initMark();       // a red sphere to mark the hit
71 
72     /** create four colored boxes and a floor to shoot at: */
73     shootables = new Node("Shootables");
74     rootNode.attachChild(shootables);
75     shootables.attachChild(makeCube("a Dragon", -2f, 0f, 1f));
76     shootables.attachChild(makeCube("a tin can", 1f, -2f, 0f));
77     shootables.attachChild(makeCube("the Sheriff", 0f, 1f, -2f));
78     shootables.attachChild(makeCube("the Deputy", 1f, 0f, -4f));
79     shootables.attachChild(makeFloor());
80     shootables.attachChild(makeCharacter());
81   }
82 
83   /** Declaring the "Shoot" action and mapping to its triggers. */
initKeys()84   private void initKeys() {
85     inputManager.addMapping("Shoot",
86       new KeyTrigger(KeyInput.KEY_SPACE), // trigger 1: spacebar
87       new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); // trigger 2: left-button click
88     inputManager.addListener(actionListener, "Shoot");
89   }
90   /** Defining the "Shoot" action: Determine what was hit and how to respond. */
91   private ActionListener actionListener = new ActionListener() {
92 
93     public void onAction(String name, boolean keyPressed, float tpf) {
94       if (name.equals("Shoot") && !keyPressed) {
95         // 1. Reset results list.
96         CollisionResults results = new CollisionResults();
97         // 2. Aim the ray from cam loc to cam direction.
98         Ray ray = new Ray(cam.getLocation(), cam.getDirection());
99         // 3. Collect intersections between Ray and Shootables in results list.
100         shootables.collideWith(ray, results);
101         // 4. Print the results
102         System.out.println("----- Collisions? " + results.size() + "-----");
103         for (int i = 0; i < results.size(); i++) {
104           // For each hit, we know distance, impact point, name of geometry.
105           float dist = results.getCollision(i).getDistance();
106           Vector3f pt = results.getCollision(i).getContactPoint();
107           String hit = results.getCollision(i).getGeometry().getName();
108           System.out.println("* Collision #" + i);
109           System.out.println("  You shot " + hit + " at " + pt + ", " + dist + " wu away.");
110         }
111         // 5. Use the results (we mark the hit object)
112         if (results.size() > 0) {
113           // The closest collision point is what was truly hit:
114           CollisionResult closest = results.getClosestCollision();
115           // Let's interact - we mark the hit with a red dot.
116           mark.setLocalTranslation(closest.getContactPoint());
117           rootNode.attachChild(mark);
118         } else {
119           // No hits? Then remove the red mark.
120           rootNode.detachChild(mark);
121         }
122       }
123     }
124   };
125 
126   /** A cube object for target practice */
makeCube(String name, float x, float y, float z)127   protected Geometry makeCube(String name, float x, float y, float z) {
128     Box box = new Box(new Vector3f(x, y, z), 1, 1, 1);
129     Geometry cube = new Geometry(name, box);
130     Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
131     mat1.setColor("Color", ColorRGBA.randomColor());
132     cube.setMaterial(mat1);
133     return cube;
134   }
135 
136   /** A floor to show that the "shot" can go through several objects. */
makeFloor()137   protected Geometry makeFloor() {
138     Box box = new Box(new Vector3f(0, -4, -5), 15, .2f, 15);
139     Geometry floor = new Geometry("the Floor", box);
140     Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
141     mat1.setColor("Color", ColorRGBA.Gray);
142     floor.setMaterial(mat1);
143     return floor;
144   }
145 
146   /** A red ball that marks the last spot that was "hit" by the "shot". */
initMark()147   protected void initMark() {
148     Sphere sphere = new Sphere(30, 30, 0.2f);
149     mark = new Geometry("BOOM!", sphere);
150     Material mark_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
151     mark_mat.setColor("Color", ColorRGBA.Red);
152     mark.setMaterial(mark_mat);
153   }
154 
155   /** A centred plus sign to help the player aim. */
initCrossHairs()156   protected void initCrossHairs() {
157     guiNode.detachAllChildren();
158     guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
159     BitmapText ch = new BitmapText(guiFont, false);
160     ch.setSize(guiFont.getCharSet().getRenderedSize() * 2);
161     ch.setText("+"); // crosshairs
162     ch.setLocalTranslation( // center
163       settings.getWidth() / 2 - guiFont.getCharSet().getRenderedSize() / 3 * 2,
164       settings.getHeight() / 2 + ch.getLineHeight() / 2, 0);
165     guiNode.attachChild(ch);
166   }
167 
makeCharacter()168   protected Spatial makeCharacter() {
169     // load a character from jme3test-test-data
170     Spatial golem = assetManager.loadModel("Models/Oto/Oto.mesh.xml");
171     golem.scale(0.5f);
172     golem.setLocalTranslation(-1.0f, -1.5f, -0.6f);
173 
174     // We must add a light to make the model visible
175     DirectionalLight sun = new DirectionalLight();
176     sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f));
177     golem.addLight(sun);
178     return golem;
179   }
180 }
181