Created
September 12, 2020 14:28
-
-
Save oeloeloel/293d5bdb75b159afce43b7d7b23f42f6 to your computer and use it in GitHub Desktop.
Bresenham's Line Algorithm in DragonRuby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# brief demonstration of Bresenham's line algorithm in DragonRuby | |
BRUSH_SIZE = 16 | |
def tick(args) | |
args.state.last_mouse_x ||= args.inputs.mouse.x | |
args.state.last_mouse_y ||= args.inputs.mouse.y | |
# set the start of the line | |
x0 = args.state.last_mouse_x | |
y0 = args.state.last_mouse_y | |
# set the end of the line | |
x1 = args.inputs.mouse.x | |
y1 = args.inputs.mouse.y | |
# draw the line | |
draw_line(args, x0, y0, x1, y1) | |
# remember the last position of the mouse | |
args.state.last_mouse_x = args.inputs.mouse.x | |
args.state.last_mouse_y = args.inputs.mouse.y | |
end | |
# draw a line using Bresenham's line algorithm | |
def draw_line(args, x0, y0, x1, y1) | |
dx = (x1 - x0).abs | |
sx = x0 < x1 ? 1 : -1 | |
dy = -(y1 - y0).abs | |
sy = y0 < y1 ? 1 : -1 | |
err = dx + dy | |
while true | |
args.outputs.sprites << [x0, y0, BRUSH_SIZE, BRUSH_SIZE, 'sprites/circle-black.png'] | |
break if x0 == x1 && y0 == y1 | |
e2 = 2 * err | |
if e2 >= dy | |
err += dy | |
x0 += sx | |
end | |
if e2 <= dx | |
err += dx | |
y0 += sy | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment