Q: Mouse - window to world translation

Question: How to translate mouse’s on-screen position to world coordinates?

// Using Top-down view like in strategy games(Battle Realms, Warcraft, etc).
// Following code produces unexpected results - it should draw a line from world’s 0,0,0 to the mouse pointer on XZ-plane.

      [java]results = new CollisionResults();
        Ray ray = new Ray(new Vector3f(inputManager.getCursorPosition().getX(), 0f, inputManager.getCursorPosition().getY()), new Vector3f(0f, -1f, 0f));
        terrain.collideWith(ray, results);
        if(results.size() > 0)
        {
            System.out.println("Collision!");
            line = new Line(Vector3f.ZERO, results.getClosestCollision().getContactPoint());
            geom = new Geometry("Line", line);
            mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            geom.setMaterial(mat);
            rootNode.attachChild(geom);
        }[/java]

Have you done the tutorials? In particular the mouse picking one which covers exactly this topic?

The picking tutorial covers a FPS mouse, which is always in the same location and watches the same direction as the camera. There was no code for strategy game style mouse picking IIRC. I would appreciate if you pointed out things if they were in the tutorials and I have missed them or try to explain things. Things like RTFM and Did you read the tutorials don’t help much. Cheers.

Never mind, I think I found it.

The tutorial called “mouse picking”? :slight_smile:

1 Like