0

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?

deblocker
  • 7,629
  • 2
  • 24
  • 59
  • I assume that you already know that floating-point calculations are sometimes not exact, but since you haven't received any answers yet: Perhaps you can just check if the difference is small enough? – Thomas Padron-McCarthy Feb 27 '17 at 18:41
  • @ThomasPadron-McCarthy: yes, my first try was to test against an epsilon, but i realized that this doesn't helps me to get the correct distance, and not even helps me to get the correct penetration vector. Still researching what i am doing wrong. – deblocker Feb 27 '17 at 20:47
  • Possible duplicate of [How to deal with floating point number precision in JavaScript?](http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Sᴀᴍ Onᴇᴌᴀ May 02 '17 at 04:00

0 Answers0