Changing Color Of Intersecting Area Of Squares
I am working on a project these days. My goal is to change the color of the intersecting areas of the two squares. I have written the code which detects whenever two squares inters
Solution 1:
Lets think a bit how we could represent the intersecting area between two squares. Surely, one of the ways to do is simply to represent it as another rectangle, whose color we simply change based on the intercepting area. To draw a rectangle, we need to know the coordinates of the upper left corner, the width and the height. Therefore the challenge is to calculate those as we drag our squares around. This should be done in the draw()
function. You already have the intersection check implemented, whats left is to calculate the new rectangle upper left point (newX, newY), width (newW) and height (newH).
In order to calculate the upper left corner, the width and height, we can add this to the block where we check for collision:
...
//block checking collisionif (i != j && squares[i].collides(squares[j])) {
squares[i].changecolor();
//set intersection colorfill(50);
//calculate parameters
newX = Math.max(squares[i].position.x, squares[j].position.x);
newY = Math.max(squares[i].position.y, squares[j].position.y);
newW = Math.min(squares[i].position.x + squares[i].w, squares[j].position.x + squares[j].w) - newX;
newH = Math.min(squares[i].position.y + squares[i].h, squares[j].position.y + squares[j].h) - newY;
//draw rectanglerect(newX, newY, newW, newH);
}
Result:
Post a Comment for "Changing Color Of Intersecting Area Of Squares"