From cfeec2cc10cdee6dd6d93b738d66a32680e76c22 Mon Sep 17 00:00:00 2001 From: Kevin Fischer Date: Sun, 26 Feb 2023 13:46:35 +0900 Subject: [PATCH] feat: Implement #to_grid_coordinates and #cell_rect for Tilemap --- lib/dragon_skeleton/tilemap.rb | 18 ++++++++++++++++++ tests/lib/dragon_skeleton/tilemap.rb | 12 ++++++++++++ 2 files changed, 30 insertions(+) diff --git a/lib/dragon_skeleton/tilemap.rb b/lib/dragon_skeleton/tilemap.rb index 0b5dd4e..c44d540 100644 --- a/lib/dragon_skeleton/tilemap.rb +++ b/lib/dragon_skeleton/tilemap.rb @@ -59,6 +59,24 @@ def render(outputs) outputs.primitives << @primitive end + # Converts a position to grid coordinates. + def to_grid_coordinates(position) + { + x: (position.x - @x).idiv(@cell_w), + y: (position.y - @y).idiv(@cell_h) + } + end + + # Returns the rectangle of the cell at the given grid coordinates. + def cell_rect(grid_coordinates) + { + x: @x + (grid_coordinates.x * @cell_w), + y: @y + (grid_coordinates.y * @cell_h), + w: @cell_w, + h: @cell_h + } + end + class RenderedPrimitive # :nodoc: Internal class responsible for rendering the tilemap. def initialize(cells, tilemap) @cells = cells diff --git a/tests/lib/dragon_skeleton/tilemap.rb b/tests/lib/dragon_skeleton/tilemap.rb index e154357..0b36896 100644 --- a/tests/lib/dragon_skeleton/tilemap.rb +++ b/tests/lib/dragon_skeleton/tilemap.rb @@ -54,6 +54,18 @@ def test_tilemap_render(args, assert) # rubocop:enable all end +def test_tilemap_to_grid_coordinates(_args, assert) + tilemap = Tilemap.new(x: 50, y: 50, cell_w: 100, cell_h: 100, grid_w: 2, grid_h: 3) + + assert.equal! tilemap.to_grid_coordinates({ x: 55, y: 55 }), { x: 0, y: 0 } +end + +def test_tilemap_cell_rect(_args, assert) + tilemap = Tilemap.new(x: 50, y: 50, cell_w: 100, cell_h: 100, grid_w: 2, grid_h: 3) + + assert.equal! tilemap.cell_rect({ x: 1, y: 2 }), { x: 150, y: 250, w: 100, h: 100 } +end + def test_tilemap_tileset_assigns_default_tile(_args, assert) tileset = TestTileset.new( default_tile: { tile_w: 50, tile_h: 50 },