Aligned rectangle to Circle collision

I know that it can be found on Google but I tried all that I could find and I kept getting errors/bugs.

In my circle class I have a function with this code:

# rect = rectangle.# @x & @y are the origin coordinates of the circle.    x = rect.right if @x > rect.right    x = rect.left if @x < rect.left    y = rect.bottom if @y > rect.bottom    y = rect.top if @y < rect.top    return Point.new(x,y).distance(origin) < @radiusPoint-class Distance implementation:

def distance(other_point) Math.hypot(other_point.x - @x, other_point.y - @y) endIt does not always work as expected (unless I tested wrong which is possible).

Is this algorithm any good?
Try doing a rectangle interception between the rectangle and the circle's bounding box, if they collide, divide the rectangle into two triangles and the circle in a triangle fan, then make some triangle interception tests.
With these kind of problems, drawing it out helps tremendously.

rectanglecollision.png


Looking at that image tell me which situations you have covered and which you have not.

Consider what should happen if the circle is inside the rectangle.

Similarly what about the case where the circle consumes the rectangle?

What should happen in these cases?

As for your code the distance check is silly.

# Basically it is thisMath.hypot(x - @x, y - @y) < @radiusInstead use the following check in this instance. You do not need the actual distance after all, you only need to know if it is greater than the radius of the circle.

(x - @x)**2 + (y - @y)**2 < @radius**2Let me know if you get stuck again.

*hugs*
Thanks for the replies.

@cidiomar

I'm looking for a fast/efficient algorithm. This method does not sound very efficient.

@zeriab

Actually my entire algorithm doesn't work...

x = rect.right if @x > rect.right x = rect.left if @x < rect.leftBut x is nil if the origin is near the center of a wide rectangle. The same goes for y. But just changing it to:

    x = rect.center    x = rect.right if @x > rect.right    x = rect.left if @x < rect.leftWon't work either because what if the rectangle is like (0,0,1000, 10) and the circle is at (250,10) with a radius of 0.5? Then

x = 500

y = 5

@x=250

@y=10

(x - @x)**2 + (y - @y)**2 < @radius**2 gives  (0-250)**2 + (5-10)**2 < 0.5**2 => 62600 < 0.25 => false (should be true).

So calculating the nearest point on the rectangle relative to the circle's origin is totally wrong. I must also handle the special case where the circle's origin is inside the rectangle. Yes it works for small rectangles but that is not good enough. It must work for all (axis aligned) rectangles no matter their size nor location. God I'm so bad at these things...

So I came up with this:

    # Check if the origin lies inside the rectangle or on the exact edge of the    # rectangle    return true if rect.contains_point(origin, true) # true means that if the point is on the edge of the rectangle that it will still count as within the rectangle.    # Get nearest point within the rectangle relative to the circle's origin.    x = @x    x = rect.right if @x > rect.right    x = rect.left if @x < rect.left    y = @y    y = rect.bottom if @y > rect.bottom    y = rect.top if @y < rect.top        # Check if the circle overlaps that nearest point.    return (x - @x)**2 + (y - @y)**2 < @radius**2So far it works for all my test cases. I hope that this keeps working for all cases 🙂 . Obviously this only works if the radius is great than 0. But I have never seen a circle with a radius <= 0 😛 .

circle.png
Excellent work!

I do not agree your entire algorithm didn't work before. After all, it did work in some cases.

That said, your new code looks much better.

How do we test it? This is a fairly critical piece of code so I suggest using more energy on testing than usual.

We cannot test all possibilities as that is practically impossible. Using the drawing again as reference, which interesting points and sections do you see if we want both border condition validation and general case validation.

Which have you tested?

*hugs*
A lot. I added the cases to my unit testing. 8 rectangles, 5 circles for a total of 11 tests. They all succeeded.

I agree, I always use unit tests on critical code like this with quiet a lot of test cases. It also has testcases for points and other circles but I removed that code to make it a bit shorter here on the forums.

stats.png

Spoiler
#<snip>#===============================================================================# Assertions Part 1#===============================================================================$imported ||= {}$imported[:nap_unit_testing] = 1.10if (($imported[:nap_script_boss] && $scripts[:unit_tests][0]) || !$imported[:nap_script_boss])module Test_Unit#------------------------------------------------------------------------------- # Variables#------------------------------------------------------------------------------- @start_time = Time.now $assert_stats = { :benchmark => 0, :tests => 0, :assertions => 0, :errors => 0, :skips => 0 } $assert = [] $assert_crashes = []#-------------------------------------------------------------------------------# Assert (base) class#------------------------------------------------------------------------------- class Assert def assert_equal(value1, value2, msg=nil) $assert_stats[:assertions] += 1 return if value1 == value2 $assert_stats[:errors] += 1 str = "#{caller[0]}} Expected: \'#{value2}\', got: \'#{value1}\'." str += " Msg: #{msg}" if msg $assert << str end def assert_not_equal(value1, value2, msg=nil) $assert_stats[:assertions] += 1 return if value1 != value2 $assert_stats[:errors] += 1 str = "#{caller[0]} Expected not: \'#{value2}\', got: \'#{value1}\'." str += " Msg: #{msg}" if msg $assert << str end def assert(value, msg=nil) $assert_stats[:assertions] += 1 return if value $assert_stats[:errors] += 1 str = "#{caller[0]} returned false." str += " Msg: #{msg}" if msg $assert << str end def self.run_all run(instance_methods(false)) end # Dynamically runs the specified methods (array of a symbol equal to the method's name) # Only runs methods that start with 'test_' def self.run(methods) me = self.new methods.each { |method| if method.to_s.start_with?('test_') $assert_stats[:tests] += 1 begin me.send(method) rescue => ex $assert_crashes << "#{ex.backtrace}: #{ex.message} (#{ex.class})" end else $assert_stats[:skips] += 1 end } end end#===============================================================================# <Test Units go below here>#===============================================================================#<snip>#===============================================================================# Circle class#=============================================================================== if $imported[:nap_circle] class Test_Circle < Assert def test_point#<snip> end # test_point def test_rectangle r1 = Rectangle.new(0, 0, 1, 1) r2 = Rectangle.new(-2, -2, 2, 2) r3 = Rectangle.new(-50, -50, 100, 100) r4 = Rectangle.new(5, 4, 1, 2) r5 = Rectangle.new(1, 0, 1, 1) r6 = Rectangle.new(0.9, 0, 1, 1) r7 = Rectangle.new(2, 2, 2, 2) r8 = Rectangle.new(0, 0, 10000, 10) c1 = Circle.new(0,0,1) c2 = Circle.new(0,10,0.1) c3 = Circle.new(5000,11,1) c4 = Circle.new(5000,12,1) c5 = Circle.new(-1,-3,1) assert(c1.collides?(r1)) assert(c1.collides?(r2)) assert(c1.collides?(r3)) assert(!c1.collides?(r4)) assert(!c1.collides?(r5)) assert(c1.collides?(r6)) assert(!c1.collides?(r7)) assert(c2.collides?(r8)) assert(!c3.collides?(r8)) assert(!c4.collides?(r8)) assert(!c5.collides?(r8)) end # test_rectangle def test_circle #<snip> end # test_circle run_all end # Test_Circle end # $imported[:nap_circle]#===============================================================================# Assertions Part 2# <Test Units go above this section>#=============================================================================== $assert_stats[:benchmark] = (Time.now - @start_time).to_s if $assert != [] p '-----------------------------------------------------------------------------' p 'Asserts:' p '-----------------------------------------------------------------------------' $assert.each_with_index { |a, index| p "#{index + 1}. #{a}"} p '-----------------------------------------------------------------------------' end if $assert_crashes.length > 0 p 'Crashes:' $assert_crashes.each_with_index { |c| p '-----------------------------------------------------------------------------' p c } p '-----------------------------------------------------------------------------' end p 'Stats:' p '-----------------------------------------------------------------------------' p "Finished in #{$assert_stats[:benchmark]} seconds." p "Tests:#{$assert_stats[:tests]} Assertions:#{$assert_stats[:assertions]} Crashed:#{$assert_crashes.length} Errors:#{$assert_stats[:errors]} Skips: #{$assert_stats[:skips]}" p '=============================================================================' end # module test_Unitend # Script Boss
Once it all works I will release them all (rectangles, points, circles, unit tests) for free of course. I need these primitives for collision detection in a simple 2d shooter in ace.
This thread is being closed, due to being solved. If for some reason you would like this thread re-opened, please report this post and leave a message why. Thank you.

Original thread: https://forums.rpgmakerweb.com/threads/aligned-rectangle-to-circle-collision.19735/