Simplify JavaScript collision detection with offset I am working on a background project that is a little interactive. Now I am using some collision detection to draw some lines and stuff.

The code I have works great but it is very bulky and hard to read.

if (background.allPixels[i].location.x - drawLineBetweenPixelRange &lt; background.allPixels[j].location.x + background.allPixels[j].width &amp;&amp;
    background.allPixels[i].location.x + background.allPixels[i].width + drawLineBetweenPixelRange &gt; background.allPixels[j].location.x &amp;&amp;
    background.allPixels[i].location.y - drawLineBetweenPixelRange &lt; background.allPixels[j].location.y + background.allPixels[j].height &amp;&amp;
    background.allPixels[i].location.y + background.allPixels[i].height + drawLineBetweenPixelRange &gt; background.allPixels[j].location.y)


It comes down to running this for the x and y coordinates:

var result = (x - a &lt; y + b) &amp;&amp; (x + b + a &gt; y)


Can this be simplified?

I was hoping if the check itself could be shortened by taking stuff out that might counter eachother.
Bug #1

Your code does not follow pattern (x - a &lt; y + b) &amp;&amp; (x + b + a &gt; y) but (x - a &lt; y + b1) || (x + b2 + a &gt; y) instead. So our refactored formula is moot! obsolete



Bug #2

A collision is detected when any of the guards trigger, not when all.



Proposed Solution

Solving both bugs, we could refactor Nikko Khresna's method:

function detectCollision(source, target, line) {
  return 
       source.location.x &lt; target.location.x + target.width + line
    || source.location.x + source.width + line &gt; target.location.x
    || source.location.y &lt; target.location.y + target.height + line
    || source.location.y + source.height + line &gt; target.location.y
  ;
}


and you can call it as follows

const collision = detectCollision(
  background.allPixels[i], background.allPixels[j], drawLineBetweenPixelRange);




Obsolete section because OP made a mistake in the formula: I'll keep it for historical reasons :)

Formula (Obsolete)

The way I see it, we could rewrite your expression:


var result = (x - a &lt; y + b) &amp;&amp; (x + b + a &gt; y)



as

var result = (x - a - b &lt; y) &amp;&amp; (x + b + a &gt; y)


and further as

var result = (x - (a + b) &lt; y) &amp;&amp; (x + (a + b) &gt; y)


now we can substitute (a + b) with offset

var result = (x - offset &lt; y) &amp;&amp; (x + offset &gt; y)


which means x and y have to be within offset distance of each other (|x-y| = abs(x-y))

var result = Math.abs(x - y) &lt; offset


Now you can substitute x, y and offset with your variables, and - as suggested in the other answer - use a method that calculates this collision for you.