Search code examples
libgdx

How to draw debug lines and shapes in LibGDX


Is there a helper system to make drawing debug lines and rectangles easier?

I have looked through related answers to similar questions but I only see answers showing how to draw individual shapes.


Solution

  • This singleton class can help to make drawing debug shapes easier. It is purposefully basic and can be easily updated to specify colour and different shapes by the user if required.

    
    import com.badlogic.gdx.graphics.Color;
    import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
    import com.badlogic.gdx.math.Matrix4;
    
    import java.util.ArrayList;
    import java.util.List;
    
    //
    // Example usage:
    // DebugDrawer.INSTANCE.drawLine(0,0,100,100);
    //
    public enum DebugDrawer {
        INSTANCE;
    
        final ShapeRenderer shapeRenderer;
        final List<Segment> segmentList;
    
        DebugDrawer() {
            shapeRenderer = new ShapeRenderer();
            segmentList = new ArrayList<>();
        }
    
        // Called from render loop - pass in view matrix, e.g., camera.combined
        public void render(Matrix4 projectionMatrix) {
            shapeRenderer.setProjectionMatrix(projectionMatrix);
    
            for (Segment segment : segmentList) {
                shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
                shapeRenderer.setColor(Color.RED);
                shapeRenderer.line(segment.x1, segment.y1, segment.x2, segment.y2);
                shapeRenderer.end();
            }
    
            segmentList.clear();
        }
    
        // Add a line to the draw list.
        public void drawLine(double x1, double y1, double x2, double y2) {
            segmentList.add(new Segment(x1, y1, x2, y2));
        }
    
        public void drawRect(double x, double y, double w, double h) {
            segmentList.add((new Segment(x,y,x+w,y)));
            segmentList.add((new Segment(x+w,y,x+w,y+h)));
            segmentList.add((new Segment(x+w,y+h,x,y+h)));
            segmentList.add((new Segment(x,y+h,x,y)));
    
        }
    
    }
    
    class Segment {
        public float x1, y1, x2, y2;
    
        public Segment(double x1, double y1, double x2, double y2) {
            this.x1 = (float) x1;
            this.y1 = (float) y1;
            this.x2 = (float) x2;
            this.y2 = (float) y2;
        }
    }
    

    From anywhere you can draw a line:

    DebugDrawer.INSTANCE.drawLine(0,0,100,100);
    

    Render all shapes at once by calling the render method from your main draw loop:

    DebugDrawer.INSTANCE.render(camera.combined);