Snapping mouse to grid

This commit is contained in:
Alexey 2025-05-20 09:31:19 +03:00
commit 74fdcd51f7
4 changed files with 29 additions and 11 deletions

View file

@ -30,7 +30,7 @@ function Grid:draw()
for x = 1, self.size.x do
for y = 1, self.size.y do
local px, py = x * Config.cellSize, y * Config.cellSize
love.graphics.circle( "fill", px, py, Config.pointRadius )
love.graphics.circle( "fill", px - Config.cellSize / 2, py - Config.cellSize / 2, Config.pointRadius)
end
end
end

View file

@ -14,5 +14,5 @@ end
-- Same as coords, but converted to global coords
function GridPoint:globalCoords()
return self.x * Config.cellSize, self.y * Config.cellSize
return self.x * Config.cellSize - Config.cellSize / 2, self.y * Config.cellSize - Config.cellSize / 2
end

View file

@ -38,6 +38,10 @@ function Line:draw()
love.graphics.circle( "fill", sx, sy, Config.linePointRadius )
local ex, ey = self.endpoint:globalCoords()
love.graphics.circle( "fill", ex, ey, Config.linePointRadius )
if #self.points == 1 then
love.graphics.setColor( Color.white )
return
end
-- Draw line
local points = {}
for _, point in ipairs( self.points ) do

View file

@ -12,21 +12,35 @@ function love.load()
GridPoint:new( 3, 3 ),
Color.red
)
line:push( GridPoint:new( 1, 2 ) )
line:push( GridPoint:new( 1, 3 ) )
line:push( GridPoint:new( 2, 3 ) )
line:push( GridPoint:new( 2, 2 ) )
line:push( GridPoint:new( 2, 1 ) )
line:push( GridPoint:new( 3, 1 ) )
line:push( GridPoint:new( 3, 2 ) )
line:push( GridPoint:new( 3, 3 ) )
gameGrid:push( line )
mouse = {
x = 0,
y = 0,
pressed = false,
lastPressed = false
}
end
-- TODO: move input interactions into module
function love.update( dt )
mouse.x, mouse.y = love.mouse.getPosition()
mouse.lastPressed = pressed
mouse.pressed = love.mouse.isDown( 1 )
end
function love.draw()
gameGrid:draw()
if mouse.pressed then
local x, y = snapCoords( Point:new( mouse.x, mouse.y ) ):coords()
local text = string.format( "%d:%d global\n%d:%d local", mouse.x, mouse.y, x, y )
love.graphics.print( text, 64, 256 )
end
end
-- Returns local coords from global
function snapCoords( point )
local x = math.ceil( point.x / Config.cellSize )
local y = math.ceil( point.y / Config.cellSize )
return GridPoint:new( x, y )
end