Easy way to draw a straight dotted line in libgdx?

I would like to draw a straight dotted line in libgdx for an Android game between the dots of the screen.

Currently, I have the following code for drawing a non-dashed line using 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 saw one more question about dashed lines , but for me it is a little kink, since it does not need its curvature, etc. I just need a straight dotted line like

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

Thought of a loop that just calculates the positions of points on a line and just draws points there? but it is really necessary, does anyone know an easier way?

+4
source share
2 answers

I am currently using this method to draw dashed 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 line vector to draw and loop it to draw points based on the desired distance to the point. In my test there was a pretty good distance:

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

This works pretty smoothly for me. If you have a better way to draw dashed lines, then please let me know.

+8
source

You could draw a series of dots, which in turn will make a dashed line. And create a for loop that draws a series of points to the end. The code will look something like this:

shapeRenderer.begin(ShapeType.Point);
for (float i = touchPos.x; i < someSprite.getX(); i += (someSprite.getY() / touchPos.y))
{
     for (float j = touchPos.y; j < someSprite.getY(); j += (someSprite.getX() / touchPos.x))
     { 
         // floats used because the increment might be decimal places. 
         shapeRenderer.point(i, j, 0);
     }
}
shapeRenderer.end();

, , i j .

, , libgdx.

+1

Source: https://habr.com/ru/post/1527791/


All Articles