0

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?

ImStupid
  • 35
  • 6

1 Answers1

0

You need something like this:

double dx = pointPositionX - positionX,
       dy = pointPositionY - positionY,
       d  = sqrt(dx * dx + dy * dy);
bool touching = d <= 3;
Sid S
  • 6,037
  • 2
  • 18
  • 24
  • No need for the `sqrt` bit -- it wastes time and reduces accuracy. Just do `bool touching = (dx * dx + dy * dy) <= 9`, instead. – Clearer Apr 14 '18 at 18:32
  • Changed it up just a little bit, and it solved my problem. Thanks alot, sir! – ImStupid Apr 14 '18 at 18:35
  • @Clearer, It adds clarity, it's easier for OP to see how it relates to his formula. – Sid S Apr 14 '18 at 18:46
  • @Clearer Yes i noticed now it was not too accurate. I would like to be more accurate though, so i tried your line. It seems to work worse though. – ImStupid Apr 14 '18 at 18:48
  • Im drawing over my snakehead with the same color of the background of my screen, so if i dont hit accurately enough it will cut my point in two. But i guess its OK – ImStupid Apr 14 '18 at 18:53
  • I increasted the d <= 3 to a higher value and now its quite accurate. Thanks to both of you. – ImStupid Apr 14 '18 at 18:58