Last active
September 30, 2020 19:02
-
-
Save amirrajan/4e8ddc996eeec525ccdd0a215d6bb351 to your computer and use it in GitHub Desktop.
DragonRuby collision and physics
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
def tick args | |
# initialization | |
args.state.x ||= 620 | |
args.state.y ||= 700 | |
args.state.dy ||= 0 | |
args.state.dx ||= 25 | |
args.state.gravity = -0.5 | |
args.state.drag_coeff = 0.05 | |
args.state.walls = [ | |
[0, 0, 1280, 100], | |
[800, 0, 100, 720] | |
] | |
args.state.elasticity = 0.6 | |
args.state.entropy_limit = 2 | |
# render | |
args.outputs | |
.solids << [0, 0, 1280, 720, 32, 32, 32] | |
args.outputs | |
.labels << [10, 680, | |
"dy: #{args.state.dy}", | |
255, 255, 255] | |
final_dy = args.state.dy.abs * | |
(args.state.drag_coeff ** 2) | |
args.outputs | |
.labels << [10, 650, | |
"drag_coeff: #{final_dy}", | |
255, 255, 255] | |
args.outputs | |
.sprites << [args.state.x, args.state.y, | |
20, 20, 'sprites/square-orange.png'] | |
args.outputs | |
.solids << args.state.walls | |
# simulation | |
# gravity | |
args.state.y += args.state.dy | |
args.state.dy += args.state.gravity | |
args.state.dy += final_dy | |
# power | |
args.state.x += args.state.dx | |
args.state.dx *= 0.9 | |
# ground collision | |
# right of box | |
collided_right = args.state | |
.walls | |
.find_all { |w| w.x > args.state.x } | |
.find { |w| [args.state.x, | |
args.state.y, 20, 20].intersect_rect? w } | |
if collided_right | |
args.state.x = collided_right.left - 20 | |
args.state.dx = args.state.dx * -1 * | |
args.state.elasticity | |
end | |
# below box | |
collided_floor = args.state | |
.walls | |
.find_all { |w| w.y < args.state.y } | |
.find { |w| [630, args.state.y, 20, 20].intersect_rect? w } | |
# collision | |
if collided_floor | |
args.state.y = collided_floor.top | |
args.state.dy = args.state.dy * -1 * | |
args.state.elasticity | |
# entropy after collision | |
reached_entropy = ( | |
args.state.dy.abs < | |
args.state.entropy_limit | |
) | |
args.state.dy = 0 if reached_entropy | |
end | |
# tunneling | |
args.state.y = 700 if args.state.y < 0 | |
end | |
$gtk.reset |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment