Skip to content

Instantly share code, notes, and snippets.

@amirrajan
Created April 24, 2026 18:37
Show Gist options
  • Select an option

  • Save amirrajan/e7356353bd3c5e46e2a3a44ea739d557 to your computer and use it in GitHub Desktop.

Select an option

Save amirrajan/e7356353bd3c5e46e2a3a44ea739d557 to your computer and use it in GitHub Desktop.
DragonRuby Game Toolkit - Grid aligned movement
class Game
attr_dr
def initialize
@cells = 32.flat_map do |x_ordinal|
18.map do |y_ordinal|
{
**Geometry.rect(x: x_ordinal * 40, y: y_ordinal * 40, w: 40, h: 40),
x_ordinal: x_ordinal,
y_ordinal: y_ordinal,
}
end
end
@walls = []
@player = {
x: 20,
y: 20,
w: 40,
h: 40,
dx: 1,
dy: 0,
anchor_x: 0.5,
anchor_y: 0.5,
path: :solid,
r: 128, g: 255, b: 128,
}
end
def tick
if inputs.mouse.key_up.left
cell = Geometry.find_intersect_rect(inputs.mouse, @cells)
if cell
if @walls.include?(cell)
@walls.delete(cell)
else
@walls << cell
end
end
end
if inputs.up_down != 0
collisions = Geometry.find_all_intersect_rect(
{ **@player, y: @player.y + inputs.up_down },
@cells,
tolerance: 0
)
if collisions.length == 2
if collisions.none? { |collision| @walls.include?(collision) }
@player.dy = inputs.up_down
@player.dx = 0
end
end
elsif inputs.left_right != 0
collisions = Geometry.find_all_intersect_rect(
{ **@player, x: @player.x + inputs.left_right },
@cells,
tolerance: 0
)
if collisions.length == 2
if collisions.none? { |collision| @walls.include?(collision) }
@player.dy = 0
@player.dx = inputs.left_right
end
end
end
@player.x += @player.dx * 2
if Geometry.find_intersect_rect(@player, @walls)
@player.x -= @player.dx * 2
end
@player.y += @player.dy * 2
if Geometry.find_intersect_rect(@player, @walls)
@player.y -= @player.dy * 2
end
outputs.background_color = [30, 30, 30]
outputs.primitives << @cells.map do |cell|
{
**Geometry.zoom_rect(rect: cell, px: -1),
path: :solid, r: 0, g: 0, b: 0, a: 128
}
end
outputs.primitives << @walls.map do |cell|
{
**Geometry.zoom_rect(rect: cell, px: -1),
path: :solid, r: 255, g: 255, b: 255, a: 128
}
end
outputs.primitives << @player
end
end
module Main
def tick args
@game ||= Game.new
@game.args = args
@game.tick
end
def reset args
@game = nil
end
end
GTK.reset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment