collision element js code example

Example 1: javascript detect collision

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.y + rect1.height > rect2.y) {
    // collision detected!
}

Example 2: how to make a collision function in p5.js

// Method
collidesWith(x, y, w, h) {
    return (
      (this.x > x &&
        this.x < x + w &&
        this.y > y &&
        this.y < y + h) ||
      (this.x + this.width > x &&
        this.x + this.width < x + w &&
        this.y > y &&
        this.y < y + h) ||
      (this.x + this.width > x &&
        this.x + this.width < x + w &&
        this.y + this.height > y &&
        this.y + this.height < y + h) ||
      (this.x > x &&
        this.x < x + w &&
        this.y + this.height > y &&
        this.y + this.height < y + h)
    );
  }