I have a bunch of axis aligned rectangles defined as follows:
function Rect(x,y,w,h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.halfWidth = this.w*0.5;
this.x1 = this.x - this.halfWidth;
this.x2 = this.x + this.halfWidth;
}
Origin (0,0) of the axis is left-top. The horizontal movement is achieved through following function:
Rect.prototype.moveX = function(dx){
this.x += dx;
this.x1 = this.x - this.halfWidth;
this.x2 = this.x + this.halfWidth;
};
Inside a game loop, during collision checking, i get, for example:
rect[1].x2 = 115.57166301905819; rect[2].x1 = 166.1619546484768;
The resulting distance along the x-axis is computed as:
dx = -50.590291629418616
This means, rect[2]
is allowed to move left maximum dx
units, i.e.:
from: rect[2].x = 341.1619546484768
to: rect[2].x = 290.5716630190582
Now, sometimes, the function moveX is resulting in following wrong calculation:
rect[2].x1 = rect[2].x - 175; // 175 is halfWidth
rect[2].x1 = 115.57166301905818 // <- less than 115.57166301905819
...which means, at the end, that rect[1]
and rect[2]
are intersecting each other (unwanted result).
Any hint to solve this issue?