jeffThompson / CollisionDetection

A book and examples on collision detection
418 stars 53 forks source link

A small optimization of Point/Circle #36

Open martys71 opened 1 year ago

martys71 commented 1 year ago

You don't need to use sqrt here. Sqrt is expensive.

// POINT/CIRCLE
boolean pointCircle(float px, float py, float cx, float cy, float r) {

  // get distance between the point and circle's center
  // using the Pythagorean Theorem
  float distX = px - cx;
  float distY = py - cy;
  float distance = sqrt( (distX*distX) + (distY*distY) );

  // if the distance is less than the circle's
  // radius the point is inside!
  if (distance <= r) {
    return true;
  }
  return false;
}

You can just compare the squares easier and faster: return distX*distX + distY*distY <= r*r;

(Thanks for the book!)