Search code examples
javascriptcollision-detection

Detect collision when a square is totally inside a circle


I have this function to detect collisions between a circle and a square

function detectCollision(square, circle) {
    let distX = Math.abs(circle.x - square.x);
    let distY = Math.abs(circle.y - square.y);

    if (distX > square.w / 2 + circle.r) return false;
    if (distY > square.w / 2 + circle.r) return false;

    if (distX <= square.w / 2) return true;
    if (distY <= square.w / 2) return true;

    let dx = distX - square.w / 2;
    let dy = distY - square.w / 2;
    return dx * dx + dy * dy <= circle.r * circle.r;
  }

It works perfectly but I need that in addition, the function detects if the square is totally inside the circle

enter image description here

it would just be like adding:

if (square is totally inside) console.log("its inside!");

Solution

  • Thanks for your answers, I had not thought about the 4 corners, but I came up with another simpler way, the distance from the origin of the circle to the origin of the square plus a bit (the "radius" of the square) must be less than radius of the circle.

    let mysquare = { x: 200, y: 200, w: 50 };
    let mycircle = { x: 110, y: 110, r: 100 };
    
    function setup() {
      createCanvas(512, 512);
      rectMode(CENTER);
    }
    
    function draw() {
      clear();
      fill(255);
      circle(mycircle.x, mycircle.y, mycircle.r * 2);
    
      mysquare.x = mouseX;
      mysquare.y = mouseY;
    
      if (isInside(mysquare, mycircle)) fill(255, 0, 0);
    
      square(mysquare.x, mysquare.y, mysquare.w);
    }
    
    function isInside(square, circle) {
      let dx = Math.abs(circle.x - square.x) + square.w/2;
      let dy = Math.abs(circle.y - square.y) + square.w/2;
    
      return dx ** 2 + dy ** 2 <= circle.r ** 2;
    }
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>