0

I have a rectangle and a matrix of rectangles.
I want to check which rectangle in the matrix collides the most with the single rectangle and change his position to fit the matrix's rectangle.
This is how my rectangles are represents

{
 x: X,
 y: Y,
 width: WIDTH,
 height: height
}

The matrix is just a simple array (9) of rectangles. As you can see in the following picture the rectangle can fit in any of the 9 squared positions, the problem is that I don't know how to calculate with which of the squares the rectangles collides the most.
Thank you very much. I'll appriciate any answer.
enter image description here

2 Answers 2

1

The "most filled" cell is the one whose centerpoint is closest to the centerpoint of your rectangle5.

You can calc the distance between any cell & rectangle5 centerpoints like this:

var dx=rect5CenterX-cellCenterX;
var dy=rect5CenterY-cellCenterY;
var distance=Math.sqrt(dx*dx+dy*dy);

The cell with the shortest distance is the cell that is most filled.

Sign up to request clarification or add additional context in comments.

1 Comment

It is good that you have mentioned that it is about centres of the rectangles, not one of their corners. I make this comment, as often the figures are drawn relative to some of their corners.
0

I guess this is what you are looking for

JSFiddle

in this we have checked each corner and center for collision.
variable x & y gives all the index of tiles with which object is colliding.

codes are commented and easy to understand;
change different variables like w,h,tw,th,originx,originy for better understanding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.