Created
February 17, 2013 04:10
-
-
Save sli/4970098 to your computer and use it in GitHub Desktop.
LOVE2D Grid Selection With A*
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
-- rounds a number to the nearest multiple of cell_size | |
-- for determining a cell in the grid | |
function grid_coords(n) | |
return math.floor(n / cell_size) * cell_size; | |
end | |
function love.conf(t) | |
t.title = "Worldthing" | |
t.author = "sli" | |
t.modules.physics = false | |
t.modules.joystick = false | |
end | |
function love.load() | |
cell_size = 50 | |
cell_tl_x = 0 | |
cell_tl_y = 0 | |
selected_cell_x = 0 | |
selected_cell_y = 0 | |
cell_selected = false | |
w = love.graphics.getWidth() | |
h = love.graphics.getHeight() | |
grid_w = w / 10 | |
grid_h = h / 10 | |
end | |
function love.mousepressed(x, y, button) | |
-- select a cell with the left mouse button | |
if button == "l" then | |
cell_selected = true | |
selected_cell_x = grid_coords(x) | |
selected_cell_y = grid_coords(y) | |
end | |
end | |
function love.draw() | |
love.graphics.setColor(255, 255, 255, 255) | |
-- draw rows | |
for r=0,grid_h do | |
love.graphics.line(0, r*cell_size, w, r*cell_size) | |
end | |
-- draw columns | |
for c=0,grid_w do | |
love.graphics.line(c*cell_size, 0, c*cell_size, h) | |
end | |
-- draw selected cell, if available | |
if cell_selected then | |
love.graphics.setColor(0, 0, 255, 255) | |
love.graphics.rectangle("fill", selected_cell_x, selected_cell_y, cell_size, cell_size) | |
end | |
-- highlight mouse cursor cell | |
love.graphics.setColor(255, 255, 255, 64) | |
love.graphics.rectangle("fill", cell_tl_x, cell_tl_y, cell_size, cell_size) | |
end | |
function love.update(dt) | |
mouse_x, mouse_y = love.mouse.getPosition() | |
-- find mouse's position in the grid | |
cell_tl_x = grid_coords(mouse_x); | |
cell_tl_y = grid_coords(mouse_y); | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment