From 8ee2233d58c25e4b88a2b46aaaa0b90ae9a49226 Mon Sep 17 00:00:00 2001 From: Tyler Scott Date: Sun, 6 Feb 2022 08:03:57 +0700 Subject: [PATCH] Refactor collision detection --- main.lua | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/main.lua b/main.lua index 63d2911..e2a52e2 100644 --- a/main.lua +++ b/main.lua @@ -201,20 +201,15 @@ function love.update(dt) if game.next_bubble.velocity_x ~= 0 or game.next_bubble.velocity_y ~= 0 then local next_x = game.next_bubble.x + game.next_bubble.velocity_x local next_y = game.next_bubble.y + game.next_bubble.velocity_y - local collision_detection_finished = false + local bubble_should_stop = false -- collision with ceiling if next_y - game.bubble_radius <= game.level_top then - local nearest_slot_index = find_nearest_slot(next_x, next_y) - game.next_bubble.x = game.bubble_slots[nearest_slot_index].x - game.next_bubble.y = game.bubble_slots[nearest_slot_index].y - game.next_bubble.velocity_x = 0 - game.next_bubble.velocity_y = 0 - collision_detection_finished = true + bubble_should_stop = true end -- collision with walls - if not collision_detection_finished then + if not bubble_should_stop then if next_x + game.bubble_radius >= game.level_right or next_x - game.bubble_radius <= game.level_left then local impact_x = game.level_left + game.bubble_radius @@ -233,7 +228,7 @@ function love.update(dt) end -- collision with another bubble - if not collision_detection_finished then + if not bubble_should_stop then for i = 1, #game.bubble_slots do local slot = game.bubble_slots[i] if slot.bubble_type ~= 0 then @@ -242,24 +237,25 @@ function love.update(dt) local dist = math.sqrt(diff_x * diff_x + diff_y * diff_y) if dist <= game.bubble_diameter then local depth = game.bubble_diameter - dist - print('depth', depth) local direction_x = diff_x / dist local direction_y = diff_y / dist next_x = next_x + direction_x * depth next_y = next_y + direction_y * depth - local nearest_slot_index = find_nearest_slot(next_x, next_y) - game.next_bubble.x = game.bubble_slots[nearest_slot_index].x - game.next_bubble.y = game.bubble_slots[nearest_slot_index].y - game.next_bubble.velocity_x = 0 - game.next_bubble.velocity_y = 0 - collision_detection_finished = true + bubble_should_stop = true break end end end end - if not collision_detection_finished then + if bubble_should_stop then + local nearest_slot_index = find_nearest_slot(next_x, next_y) + game.bubble_slots[nearest_slot_index].bubble_type = game.next_bubble.bubble_type + game.next_bubble.x = game.bubble_slots[nearest_slot_index].x + game.next_bubble.y = game.bubble_slots[nearest_slot_index].y + game.next_bubble.velocity_x = 0 + game.next_bubble.velocity_y = 0 + else game.next_bubble.x = next_x game.next_bubble.y = next_y end