Search code examples
javajmonkeyengine

Draw a rectangle with JMonkey


How can I draw a simple red box?


Solution

  • Quad is a predefined mesh (or shape) that has a height, a width and lies on the X/Y plane. A Geometry is needed for rendering the mesh and a Material will define it's color. You also have to synchronize the position of the rectangle with the position of the mouse cursor. All these things are necessary and you'll always end up with a minimum amount of code.

    public void simpleInitApp() {
        // Create red transparent material
        Material mat = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setColor("Color", new ColorRGBA(1, 0, 0, 0.5f)); // 0.5f is the alpha value
    
        // Activate the use of the alpha channel
        mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha);
    
        // Create rectangle of size 10x10
        Geometry mouseRect = new Geometry("MouseRect", new Quad(10, 10));
        mouseRect.setMaterial(mat);
        guiNode.attachChild(mouseRect);
    }
    
    public void simpleUpdate(float tpf) {
        // Move the rectangle to the cursor position
        Vector2f cursor = inputManager.getCursorPosition();
        guiNode.getChild("MouseRect").setLocalTranslation(cursor.x, cursor.y, 0);
    }
    

    The origin of the rectangle is on its lower left corner. You may want to use an offset to center the rectangle at the cursor position:setLocalTranslation(cursor.x - 5, cursor.y - 5, 0).

    More information about
    Shapes: http://hub.jmonkeyengine.org/wiki/doku.php/jme3:advanced:shape
    Materials: http://hub.jmonkeyengine.org/wiki/doku.php/jme3:intermediate:how_to_use_materials

    As an alternative you could also replace the mouse cursor with a custom image.
    See http://hub.jmonkeyengine.org/forum/topic/custom-mouse-cursor-committed/