Lemur has a robust picking subsystem that uses JME’s standard ray collision code. In this Lemur Gem, I add simple mouse picking to the app already built in Lemur Gem #1 and Lemur Gem #2
When you initialize Lemur’s GuiGlobals, it automatically adds the MouseAppState that does scene picking. It also adds the guiNode and rootNode to the pickable scene roots automatically. This demo uses that automatic setup. It is also possible to use the MouseAppState without the rest of Lemur but for simplicity I won’t be covering that here.
The first thing I did to the existing gems demo was to add a few more boxes so that we have more than one thing to pick.
The box creation now looks like this:
for( int i = 0; i < 5; i++ ) {
Box b = new Box(1, 1, 1);
Geometry geom = new Geometry("Box", b);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
geom.setMaterial(mat);
geom.setLocalTranslation(-8 + i * 4, 0, -4);
...snip listener setup....
rootNode.attachChild(geom);
}
So we will have 5 blue boxes in a nice row in front of us. For each of those boxes, I simply add a mouse listener:
MouseEventControl.addListenersToSpatial(geom,
new DefaultMouseListener() {
@Override
protected void click( MouseButtonEvent event, Spatial target, Spatial capture ) {
Material m = ((Geometry)target).getMaterial();
m.setColor("Color", ColorRGBA.Red);
if( event.getButtonIndex() == MouseInput.BUTTON_LEFT ) {
target.move(0, 0.1f, 0);
} else {
target.move(0, -0.1f, 0);
}
}
@Override
public void mouseEntered( MouseMotionEvent event, Spatial target, Spatial capture ) {
Material m = ((Geometry)target).getMaterial();
m.setColor("Color", ColorRGBA.Yellow);
}
@Override
public void mouseExited( MouseMotionEvent event, Spatial target, Spatial capture ) {
Material m = ((Geometry)target).getMaterial();
m.setColor("Color", ColorRGBA.Blue);
}
});
When the mouse first hovers over a cube this will set the color to yellow. If the mouse stops hovering over the cube then the color is switched back to blue.
If the cube is clicked on then it is turned red and raised up or down 0.1 units depending on the mouse button.
Full PickDemo.java source code here: Lemur/PickDemo.java at master · jMonkeyEngine-Contributions/Lemur · GitHub
And here is a short video demonstrating the code above:
Edit: fixed the source link since googlecode is dead.