Software Software
asked on
Algorithm: Detect a collision
Hello,
I have on my program several rectangles. The rectangles are moveable. But Collisions should be avoided when moving.
For example:
When I move the blue rectangle on the red rectangle then a collision happened.
The blue rectangle should then be placed under the red rectangle.
But then a collision with the green rectangle happens.
So rectangle blue should be placed between rectangle green and red.
I draw a rectangle after mouseUp Event.
How can I solve this problem?
Result:
Thank you
I have on my program several rectangles. The rectangles are moveable. But Collisions should be avoided when moving.
For example:
When I move the blue rectangle on the red rectangle then a collision happened.
The blue rectangle should then be placed under the red rectangle.
But then a collision with the green rectangle happens.
So rectangle blue should be placed between rectangle green and red.
I draw a rectangle after mouseUp Event.
How can I solve this problem?
Result:
Thank you
Well, the general approach:
1) You need a list of all objects.
2) You need a method to detect intersection or overlapping of objects.
3) You iterate thru that list and
3a) test for intersections.
3b) when an intersection is found, adjust your object and go to 3a).
1) You need a list of all objects.
2) You need a method to detect intersection or overlapping of objects.
3) You iterate thru that list and
3a) test for intersections.
3b) when an intersection is found, adjust your object and go to 3a).
Here are some examples for you to test out your program. Post your program if you are having trouble with any of these intersections.
+-----+ +-----------+
| | | |
+---| |-----------+ | +-----+ |
| | | | | | | |
+---| |-----------+ | | | |
| | | | | |
+-----+ | | | |
| +-----+ |
| |
+-----+ +-----------+
| |
+--------------+
| |
+--------------+
| |
+-----+
+-----+
| |
| +--------------+
| | |
| +--------------+
| |
| |
| +--------------+
+---| |
+--------------+
By sliding one of the windows around, you can come up with a few more examples (like where two bottom points are hidden by the moved rectangle).
This question needs an answer!
Become an EE member today
7 DAY FREE TRIALMembers can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Checks: Is the moved blue rectangle
1. completely or partially inside the red rectangle? or
2. completely including the red rectangle? or
3. Else: not intersecting the red rectangle at all.
Do checks with all the other non-blue rectangles.