Search code examples
c++matharduinoadafruit

How to check if two circles drawn on an Adafruit TFT screen are touching eachother?


im making (or rather, trying to make, lol) a snake game on a Adafruit TFT 1.8 screen. Then i ofcourse need the snakehead to know when it hits the "point", and therefore i need to know when the two circles which are of even size are touching eachother. However, my function for this is not working (in other words printing "NOT TOUCHING").

Im trying to follow this formula: (sqrt(dx2 + dy2))

The radius of both circles are 3, and i get the center for the formula from adding the screen position x and y of the circles together (am i even getting the centers correctly?).

void pointCondition() {
  double centerPoint = pointPositionX + pointPositionY;
  double centerSnakeHead = positionX + positionY;
  int distanceBetweenCenter = (sqrt(centerPoint * 3 + centerSnakeHead * 3));
  int weight = 3 / 2;

  if (distanceBetweenCenter < weight) {
    Serial.println("TOUCHING");
  } else {
    Serial.println("NOT TOUCHING");
  }

}

Can you see what i am doing wrong?


Solution

  • You need something like this:

    double dx = pointPositionX - positionX,
           dy = pointPositionY - positionY,
           d  = sqrt(dx * dx + dy * dy);
    bool touching = d <= 3;