1
\$\begingroup\$

I have been looking at codes of several open source 2d games and I have found this function.

GetLineCollisionHit(Vector2 Position1, int Width1, int Height1, Vector2 Position2, int Width2, int Height2)
    {
      int tile1X= Position1.X + Width1 / 16.0);
      int tile1Y= Position1.Y + Height1 / 16.0);
      int tile2X= Position2.X + Width2 / 16.0);
      int tile2Y= Position2.Y + Height2 / 16.0);
        do
        {
          int dx= Math.Abs(tile1X- tile2X);
          int dy= Math.Abs(tile1Y- tile2Y);
          if (tile1X== tile2X && tile2Y== tile1Y)
            return true;
          if (dx> dy)
          {
            if (tile1X< tile2X)
              ++tile1X;
            else
              --tile1X;
            (check collision)
          }
          else
          {
            if (tile1Y< tile2Y)
              ++tile1Y;
            else
              --tile1Y;
            (return true if collision)
          }
        }
        while (true);
        return false;
    }

What is really checking is if there is any collision of solid tiles between two points, for this look for the line between the two tiles. But I do not know if it is a coding problem since it is not implementing neither Bresenham's line algorithm nor DDA or similar. So what are you trying to find in this line dx>dy? What sense does it have to advance x while x > y since that way a line is not correctly created.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This looks to me like a version of DDA. The naming of variables is absolutely atrocious, making it really hard to understand.

The check for whether absolute value of dx or dy is greater is so that it can march 1 pixel at a time along the line. If dx is greater, the slope is between -1 and 1, so the "run" is greater than the "rise". Every time we increment our horizontal position, the vertical position will change by less than or equal to 1. So we're guaranteed to hit every pixel on the line. But if dy is greater, then the slope is between 1 and infinity (or -1 and -infinity). So you want to increment the vertical component by one and the horizontal component will always vary by less than or equal to 1, but greater than -1, meaning you'll still hit every pixel on the line.

\$\endgroup\$
1
  • \$\begingroup\$ Names changed, to understand. \$\endgroup\$ Jan 15, 2018 at 18:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .