I have two rectangles defined by their respective left, right, top and bottom. I'm trying to prevent the collisions for these two rectangles but I cannot find a working solution. I am obtaining the size of the overlapping part with success using this method:

double _left = max(first.left, other.left);
double _right = min(first.right, other.right);
double _bottom = min(first.bottom, other.bottom);
double _top = max(first.top, other.top);

double _collisionsWidth = (_left - _right).abs();
double _collisionHeight = (_bottom - _top).abs();

_left, _right, _bottom and _top are referred to the intersection, where the width and height are always positive. Having this how can I update the position of the first rectangle updating its center so that no overlap occurs, how would I do it?

  • \$\begingroup\$ We have lots of existing Q&A on collision resolution for axis-aligned bounding boxes, and it's covered extensively in documents you can find a simple search away. How have you tried applying this wealth of published knowledge to your problem so far? \$\endgroup\$ – DMGregory Mar 21 '20 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.