a function that uses bresenham's line algorithm to take two points and returns an array of points that the line passes through in csharp

main.cs
using System.Collections.Generic;

public static class BresenhamsLineAlgorithm
{
    public static List<Point> GetPointsOnLine(Point pointA, Point pointB)
    {
        List<Point> pointsOnLine = new List<Point>();

        int deltaX = Mathf.Abs(pointB.x - pointA.x);
        int deltaY = Mathf.Abs(pointB.y - pointA.y);
        int signX = pointA.x < pointB.x ? 1 : -1;
        int signY = pointA.y < pointB.y ? 1 : -1;
        int error = deltaX - deltaY;

        pointsOnLine.Add(pointA);

        while (pointA.x != pointB.x || pointA.y != pointB.y)
        {
            pointsOnLine.Add(pointA);

            int error2 = error * 2;

            if (error2 > -deltaY)
            {
                error -= deltaY;
                pointA.x += signX;
            }

            if (error2 < deltaX)
            {
                error += deltaX;
                pointA.y += signY;
            }
        }

        return pointsOnLine;
    }
}
950 chars
39 lines

This function calculates all the points on the line between two points pointA and pointB using Bresenham's line algorithm. The returned value is a List of Point objects. The Point class represents a point on the Cartesian plane with x and y coordinates.

gistlibby LogSnag