The code should return the name of the object I click with the mouse.
The problem is, the position seems not to be right, because sometimes I click on an object and I get no name and sometimes I click nothing and I get the name of an object.
Hope somebody sees my error! thanks!!!
import com.jme.input.MouseInput;
import com.jme.input.action.InputActionEvent;
import com.jme.input.action.MouseInputAction;
import com.jme.intersection.BoundingPickResults;
import com.jme.intersection.PickResults;
import com.jme.math.Ray;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.scene.Node;
import com.jme.scene.Text;
import com.jme.system.DisplaySystem;
/**
* <code>MousePick</code>
* @author Mark Powell
* @version
*/
public class MousePick extends MouseInputAction {
private Camera camera;
private Node scene;
private DisplaySystem display = DisplaySystem.getDisplaySystem();
public MousePick(Camera camera, Node scene) {
this.camera = camera;
this.scene = scene;
}
public void performAction(InputActionEvent evt) {
if (MouseInput.get().isButtonDown(0)) {
Vector2f screenPos = new Vector2f();
// Get the position that the mouse is pointing to
screenPos.set(MouseInput.get().getXAbsolute(), MouseInput.get().getYAbsolute());
// Get the world location of that X,Y value
Vector3f worldCoords = display.getWorldCoordinates(screenPos, 1.0f);
// Create a ray starting from the camera, and going in the direction
// of the mouse's location
final Ray mouseRay = new Ray(camera.getLocation(), worldCoords
.subtractLocal(camera.getLocation()));
mouseRay.getDirection().normalizeLocal();
PickResults results = new BoundingPickResults();
results.setCheckDistance(true);
scene.findPick(mouseRay,results);
if(results.getNumber() > 0) {
for(int i = 0; i < results.getNumber(); i++) {
System.out.println(results.getPickData(i).getTargetMesh().getName() + " " + results.getPickData(i).getDistance());
//if(i != results.getNumber() -1) {
//System.out.println("Not Found");
//}
}
}
results.clear();
}
}
}