From 8b44f39cf97794272306aa51cc9903d94ed0ddd2 Mon Sep 17 00:00:00 2001 From: erichan1 <30481032+erichan1@users.noreply.github.com> Date: Tue, 3 Jun 2025 21:08:28 -0700 Subject: [PATCH] Document collision fix --- notes.md | 2 +- scripts/boxgame.js | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/notes.md b/notes.md index c8cf9c9..ee586b0 100644 --- a/notes.md +++ b/notes.md @@ -1,5 +1,5 @@ Problems: - - Interesting bug - If you make height or width of a component negative. componentColHandle fails to work. + - Fixed: collision detection now works even when a component has a negative height or width. - allow objects to skid for componentColHandle() - try to delete the obstacle after it goes off screen. right now I just add obstacles forever. - collision handling doesn't work with moving obstacles. currently works by reversing myBox speed. if myBox has no speed, no work. diff --git a/scripts/boxgame.js b/scripts/boxgame.js index 0bd00bf..4c9aff8 100644 --- a/scripts/boxgame.js +++ b/scripts/boxgame.js @@ -113,16 +113,25 @@ function componentColHandle(myComponent,myComponent2){ } //returns boolean if collision between components occurs -function componentColDetect(myComponent,myComponent2){ - if(myComponent.x+myComponent.width>=myComponent2.x - && myComponent.y+myComponent.height>=myComponent2.y - && myComponent.x<=myComponent2.x+myComponent2.width - && myComponent.y<=myComponent2.y+myComponent2.height) { - return true; - } - else { - return false; - } +function componentColDetect(myComponent, myComponent2){ + const comp1 = { + left: Math.min(myComponent.x, myComponent.x + myComponent.width), + right: Math.max(myComponent.x, myComponent.x + myComponent.width), + top: Math.min(myComponent.y, myComponent.y + myComponent.height), + bottom: Math.max(myComponent.y, myComponent.y + myComponent.height) + }; + + const comp2 = { + left: Math.min(myComponent2.x, myComponent2.x + myComponent2.width), + right: Math.max(myComponent2.x, myComponent2.x + myComponent2.width), + top: Math.min(myComponent2.y, myComponent2.y + myComponent2.height), + bottom: Math.max(myComponent2.y, myComponent2.y + myComponent2.height) + }; + + return !(comp1.right < comp2.left || + comp1.left > comp2.right || + comp1.bottom < comp2.top || + comp1.top > comp2.bottom); } //checks how many obstacles are on screen. Goes through myObstacles array.