-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBresenham.cs
85 lines (77 loc) · 2.22 KB
/
Bresenham.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
namespace TinyKnight
{
// Implementation the Bresenham algorithm
// as described in: https://deepnight.net/tutorial/bresenham-magic-raycasting-line-of-sight-pathfinding/
public static class Bresenham
{
public static List<Point> GetLine(Point start, Point end)
{
return GetLine(start.X, start.Y, end.X, end.Y);
}
public static List<Point> GetLine(int x0, int y0, int x1, int y1)
{
var points = new List<Point>();
var swapXY = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
int temp;
if (swapXY)
{
// Swap x0 and y0.
temp = x0;
x0 = y0;
y0 = temp;
// Swap x1 and y1.
temp = x1;
x1 = y1;
y1 = temp;
}
if (x0 > x1)
{
// Swap x0 and x1.
temp = x0;
x0 = x1;
x1 = temp;
// Swap y0 and y1.
temp = y0;
y0 = y1;
y1 = temp;
}
var deltaX = x1 - x0;
var deltaY = Math.Abs(y1 - y0);
var error = deltaX / 2;
var y = y0;
var yStep = y0 < y1 ? 1 : -1;
if (swapXY)
{
// Y / X
for (var x = x0; x <= x1; x++)
{
points.Add(new Point(x: y, y: x));
error -= deltaY;
if (error < 0)
{
y += yStep;
error += deltaX;
}
}
}
else
{
// X / Y
for (var x = x0; x <= x1; x++)
{
points.Add(new Point(x, y));
error -= deltaY;
if (error < 0)
{
y += yStep;
error += deltaX;
}
}
}
return points;
}
}
}