How do I draw a dotted or dashed line?

Posted by Gagege on Game Development See other posts from Game Development or by Gagege
Published on 2012-12-07T17:23:35Z Indexed on 2012/12/07 17:39 UTC
Read the original article Hit count: 229

Filed under:
|

I'm trying to draw a dashed or dotted line by placing individual segments(dashes) along a path and then separating them. The only algorithm I could come up with for this gave me a dash length that was variable based on the angle of the line. Like this:

private function createDashedLine(fromX:Float, fromY:Float, toX:Float, toY:Float):Sprite 
{
    var line = new Sprite();
    var currentX = fromX;
    var currentY = fromY;
    var addX = (toX - fromX) * 0.0075;
    var addY = (toY - fromY) * 0.0075;
    line.graphics.lineStyle(1, 0xFFFFFF);

    var count = 0;

    // while line is not complete
    while (!lineAtDestination(fromX, fromY, toX, toY, currentX, currentY))
    {
        /// move line draw cursor to beginning of next dash
        line.graphics.moveTo(currentX, currentY);

        // if dash is even
        if (count % 2 == 0)
        {
            // draw the dash
            line.graphics.lineTo(currentX + addX, currentY + addY);
        }

        // add next dash's length to current cursor position
        currentX += addX;
        currentY += addY;

        count++;
    }
    return line;
}

This just happens to be written in Haxe, but the solution should be language neutral. What I would like is for the dash length to be the same no matter what angle the line is. As is, it's just adding 75 thousandths of the line length to the x and y, so if the line is and a 45 degree angle you get pretty much a solid line. If the line is at something shallow like 85 degrees then you get a nice looking dashed line. So, the dash length is variable, and I don't want that. How would I make a function that I can pass a "dash length" into and get that length of dash, no matter what the angle is?

If you need to completely disregard my code, be my guest. I'm sure there's a better solution.

© Game Development or respective owner

Related posts about math

Related posts about lines