Yehonatan
Yehonatan

Reputation: 3225

collision between object and a matrix of objects on canvas

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

Upvotes: 0

Views: 91

Answers (2)

singhiskng
singhiskng

Reputation: 511

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.

Upvotes: 0

markE
markE

Reputation: 105015

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.

Upvotes: 1

Related Questions