Skip to content

Instantly share code, notes, and snippets.

@codingbychanche
Last active April 9, 2022 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingbychanche/e3b53750edaab0170bced2eee46c065e to your computer and use it in GitHub Desktop.
Save codingbychanche/e3b53750edaab0170bced2eee46c065e to your computer and use it in GitHub Desktop.
A collection of collision detection algorithms. Written in "MonkeyX". Easily portable to any other language :-)
'************************************************************************************************
' Collision detection
'
' This class checks if a given set of coordinates overlaps with a given area
' It retruns 'true' if the areas/ coordinates do overlap and 'false' if they do not
'
' 01.04.2015 Fixed 'circ_with_circ'
' 27.12.2015 Added 'rect_in_rect'
'
'************************************************************************************************
Class GDo_overlap
' Check if a certain pixel at x/y coordinates is within an rectangular area
'
' x,y coordinates to check
' xr,yr upper, right corner of rectancular area to check
' width,height Size of rectancular area
'
Function pixel_with_rect (x:Int,y:Int,xr:Int,yr:Int,width:Int,height:Int)
If ((x>xr) And (x<xr+width)) And ((y>yr) And (y<yr+height)) Then
Return (True)
Else
Return (false)
Endif
end
' Check if two rectancular areas do overlap
'
' x,y upper left corner of area to check
' xw,yw width and height of area to check
'
' xr,yr upper left corner of area to check
' xw,yw width and height of area to check
'
' Revised: 2/2016
Function rect_with_rect (x1:Int,y1:Int,xw1:Int,yh1:Int,x2:Int,y2:Int,xw2:Int,yh2:Int)
If x1+xw1<x2 Or x2+xw2<x1 Or y1+yh1<y2 Or y2+yh2<y1 Then
Return False
Else
Return true
endif
end
' Check if on of two rectancuar areas lies within the other
'
' x,y upper left corner of area to check
' xw,yw width and height of area to check
'
' xr,yr upper left corner of area to check
' xw,yw width and height of area to check
'
Function rect_in_rect (x:Int,y:Int,xw:Int,yh:Int,xr:Int,yr:Int,xrw:Int,yrh:Int)
' Upper left corner
If ((x>xr) And (x<xr+xrw)) And ((y>yr) And (y<yr+yrh)) Then
If ((x+xw>xr) And (x+xw<xr+xrw)) And ((y>yr) And (y<yr+yrh)) Then
If ((x>xr) And (x<xr+xrw)) And ((y+yh>yr) And (y+yh<yr+yrh)) Then
If ((x+xw>xr) And (x+xw<xr+xrw)) And ((y+yh>yr) And (y+yh<yr+yrh)) Then
Return (True)
Endif
Endif
Endif
Endif
Return (False)
End
' Check if two circles do overlap
'
' x1/x2 and y1/y2 r1/r2 Pos and radius of the two circles to check
'
' Check if two circles do overlap
'
' x1/x2 and y1/y2 r1/r2 Pos and radius of the two circles to check
'
Function circ_with_circ (x1:Int,y1:Int,r1:Int,x2:Int,y2:Int,r2:Int)
Local dx:Float=x1-x2
Local dy:Float=y1-y2
Local r:Int=r1+r2
If dx*dx+dy*dy<r*r Then
Return True
Else
Return False
endif
End
End
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment