Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way of drawing a straight dotted line in libgdx?

I would like to draw a straight dotted line in libgdx for android game between to points of the screen.

Currently I have the following code to draw the not-dotted line, using a ShapeRenderer:

shapeRenderer.begin(ShapeType.Line);
//draws normal line, would prefer it dotted...............
shapeRenderer.line(touchPos.x, touchPos.y, someSprite.getX(), someSprite().getY());
shapeRenderer.end();

I have seen another question about dotted lines, but it is a bit of an overkill for me since I don't need it curved etc. I just need a straight dotted line, like

...............................................................................................

Was thinking about having a loop that just calculates the positions of the dots on the line and just draws dots there? but is that really necessary, does anyone know a simpler way?

like image 961
donfuxx Avatar asked Feb 19 '14 21:02

donfuxx


1 Answers

Currently I am using this method to draw the dotted lines:

/**
 * Draws a dotted line between to points (x1,y1) and (x2,y2).
 * @param shapeRenderer
 * @param dotDist (distance between dots)
 * @param x1
 * @param y1
 * @param x2
 * @param y2
 */
private void drawDottedLine(ShapeRenderer shapeRenderer, int dotDist, float x1, float y1, float x2, float y2) {
    shapeRenderer.begin(ShapeType.Point);

    Vector2 vec2 = new Vector2(x2, y2).sub(new Vector2(x1, y1));
    float length = vec2.len();
    for(int i = 0; i < length; i += dotDist) {
        vec2.clamp(length - i, length - i);
        shapeRenderer.point(x1 + vec2.x, y1 + vec2.y, 0);
    }

    shapeRenderer.end();
}

So basically I calculated the vector of the line to draw and looped through it to draw the dots based on the desired dot distance. A distance of 10 looked quite nice in my test:

 drawDottedLine(shapeRenderer, 10, x1, y1, x2, y2);

This works quite smooth for me. If you have a nicer way of drawing dotted lines then please let me know.

like image 79
donfuxx Avatar answered Sep 25 '22 01:09

donfuxx