Rectagle Circle Collision, something strange in this.

Discuss any general programming issues here
Post Reply
Bugala
Posts: 1178
Joined: Sun Feb 14, 2010 7:11 pm

Rectagle Circle Collision, something strange in this.

Post by Bugala »

I googled Circle-Rectangle Collision, and they seem to suggst following:

Code: Select all

local math_abs = math.abs

function circlerect_colliding(cx, cy, cr, rx, ry, rw, rh)
  circleDistance_x = math_abs(cx - rx)
  circleDistance_y = math_abs(cy - ry)

  if circleDistance_x > (rw / 2 + cr) then
  	return false
  end

  if circleDistance_y > (rh / 2 + cr) then 
  	return false
  end

  if circleDistance_x <= (rw / 2) then 
  	return true
  end

  if circleDistance_y <= (rh / 2) then
  	return true
  end

  cornerDistance_sq = (circleDistance_x - rw / 2) ^ 2 + (circleDistance_y - rh / 2) ^ 2

  return (cornerDistance_sq <= (cr ^ 2))
end
what seems strange to me is for example this part:

Code: Select all

if circleDistance_x > (rw / 2 + cr) then
  	return false
  end
for it don't seem to work.

Lets take an example of Rectangle starting at X=1 and Circle at X=200

Rectangles width is 100 and Circles Radius is 100 as well.

Therefore using this calculation, Xdistance is 199.

Using
(rw / 2 + cr) =
100/2 + 100 =
50 + 100 =
150

In reality Rectangles Width being 100, would make it reach to X spot 101.
Circle on the other hand from X=200 with 100 Radius, would reach X spot 100.
Meaning there is overlap (=collision) in spot X100 and X101 between those two.

Yet these Circle-Rectangle collisions are giving FALSE as the result in this kind of case.

What am I not getting here, or are they all really wrong about their Circle-Rectangle Collision detection code?
Bugala
Posts: 1178
Joined: Sun Feb 14, 2010 7:11 pm

Re: Rectagle Circle Collision, something strange in this.

Post by Bugala »

By the way, here is the one I settled with, used ChatGPT to get this (not direct copy of the result):

Code: Select all

Function CollisionCheck_Circle_And_Rectangle(CircleX, CircleY, CircleR, RectX, RectY, RectWidth, RectHeight)
    Local ClosestX = Clamp(CircleX, RectX, RectX + RectWidth)
    Local ClosestY = Clamp(CircleY, RectY, RectY + RectHeight)
    Local DistanceX = CircleX - ClosestX
    Local DistanceY = CircleY - ClosestY
    Return(   ((DistanceX * DistanceX) + (DistanceY * DistanceY)) < (CircleR * CircleR)   );
EndFunction


Function Clamp(Value, MinValue, Maxvalue)
	If Value < MinValue
    		Return(MinValue)
  	ElseIf Value > MaxValue
    		Return(MaxValue)
  	Else
    		Return(Value)
  	EndIf
EndFunction
But still wondering about that other example.
Post Reply