Picking terrain with the mouse (5 posts)

  • Profile picture of whodunit whodunit said 3 months, 2 weeks ago:

    When I try to pick terrain with my mouse, the further off-center that I get off of the chunk of terrain, the further off my mouse is from my ‘mark’.
    The code I am using to try to attempt this:

     if (name.equals("Shoot")) {
                    fpsText.setText("Shooting!");
                    CollisionResults results = new CollisionResults();
                    Vector2f click2d = inputManager.getCursorPosition();
                    Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone();
                    Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d);
                    dir.subtractLocal(click3d).normalizeLocal();
                    Ray ray = new Ray(click3d, dir);
                    //Ray ray = new Ray(cam.getLocation(), cam.getDirection());
                    rootNode.collideWith(ray, results);
    
                    if (results.size() > 0) {
                        if (!result.getGeometry().getName().equals("MARK")) {
    
                            CollisionResult closest = results.getClosestCollision();
                            mark.setLocalTranslation(closest.getContactPoint());
                            rootNode.attachChild(mark);
                        }
                    } else {
                        rootNode.detachChild(mark);
                    }
                }
    

    I am not sure why it is ‘marking’ further off the larger the distance is from the center; I get the same results with a Box-shaped Geometry, unless I take off the line dir.subtractLocal(click3d).normalizeLocal(); .

  • Profile picture of thetoucher thetoucher350p said 3 months, 2 weeks ago:

    your direction vector looks a bit funky, try using this …

    Vector3f origin    = main.getCamera().getWorldCoordinates(main.getInputManager().getCursorPosition(), 0.0f);
    Vector3f direction = main.getCamera().getWorldCoordinates(main.getInputManager().getCursorPosition(), 0.3f);
    direction.subtractLocal(origin).normalizeLocal();
  • Profile picture of whodunit whodunit said 3 months, 2 weeks ago:

    Ah, that is a lot more readable and works to fix the problem, thanks :)

    Is there a reason that the other code works on a Box-shaped Geometry without the normalization?

  • Profile picture of thetoucher thetoucher350p said 3 months, 2 weeks ago:

    perhaps because you were subtracting click3d twice, and you were commenting out the second occurrence while commenting out the localize, I think the double subtraction was your issue.

  • Profile picture of whodunit whodunit said 3 months, 2 weeks ago:

    Yes, it was the subtraction of click3d twice that was doing it. Thank you!