_TITLE "Bounding Box Collision Detection" ' 2020-03-03 update for Toolbox
' 2019-08-30 rewrite this so mouse box never gets inside the sides of box for maze study
'
' Collision - Test 1 orig by johnno copied and mod b+ 2018-06-10
'
' Bounding Box
'
' 2018-06-10 mod by B+ change for x, y, w, h of images
' by readjusting all the variables and use STEP for box drawing
' Generalize the specific gosub routine from this one app so can reuse IN ANY APP using sprites / tiles / images
' 2020-08-28 WTH happened to this code? OH! If collision = 1 not -1 or just If Collision... fixed
CONST box1Width
= 400, box1Height
= 100, box1Left
= 400 - box1Width
/ 2, box1Top
= 300 - box1Height
/ 2 ' center box CONST mouseboxWidth
= 50, mouseboxHeight
= 40 ' mouse controled box
SCREEN _NEWIMAGE(800, 600, 32) '<<< something more standard center is 400, 300 DIM hey$
(5), k$
, ombx
, omby
, mouseBoxX
, mouseBoxY
, r$
, f&
, b&
, lim
hey$(0) = "Hey!"
hey$(1) = "I beg your pardon."
hey$(2) = "Bang!"
hey$(3) = "Yikes!"
hey$(4) = "Ouch!"
hey$(5) = "Watch where you are going."
LINE (box1Left
, box1Top
)-STEP(box1Width
, box1Height
), _RGB32(255, 255, 255), BF
ombx = mouseBoxX: omby = mouseBoxY 'old mouse x, y
mouseBoxX
= _MOUSEX - mouseboxWidth
/ 2 mouseBoxY
= _MOUSEY - mouseboxHeight
/ 2
IF collision%
(box1Left
, box1Top
, box1Width
, box1Height
, mouseBoxX
, mouseBoxY
, mouseboxWidth
, mouseboxHeight
) THEN mouseBoxX = ombx: mouseBoxY = omby
lim = 1
lim = 200
LINE (mouseBoxX
, mouseBoxY
)-STEP(mouseboxWidth
, mouseboxHeight
), _RGB32(255, 128, 0), BF
'<<< use step with width and height
' Description:
' Check for the collison of 2 rectangles given their top left x, y and width, height.
' Returns true value -1, if they overlap and false 0 if they don't.
FUNCTION collision%
(b1x
, b1y
, b1w
, b1h
, b2x
, b2y
, b2w
, b2h
) ' x, y represent the box left most x and top most y
' w, h represent the box width and height which is the usual way sprites / tiles / images are described
' such that boxbottom = by + bh
' and boxright = bx + bw
'so the specific gosub above is generalized to a function procedure here!
IF (b1y
+ b1h
< b2y
) OR (b1y
> b2y
+ b2h
) OR (b1x
> b2x
+ b2w
) OR (b1x
+ b1w
< b2x
) THEN collision% = 0
collision% = -1 ' Collsion is true