Advertisement
Rafpast

lineOnGrid

Aug 13th, 2021 (edited)
1,620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. void mousePressed()
  2. {
  3.   mouseOldCordX = mouseX/cellSize;
  4.   mouseOldCordY = mouseY/cellSize;
  5. }
  6.  
  7. void mouseReleased()
  8. {
  9.   mouseNewCordX = mouseX/cellSize;
  10.   mouseNewCordY = mouseY/cellSize;
  11.  
  12.   lineDrawing();
  13. }
  14.  
  15. void lineDrawing()
  16. {
  17.   int deltaX = mouseNewCordX - mouseOldCordX, deltaY = mouseNewCordY - mouseOldCordY;
  18.   int gradient = deltaY + deltaY, error = gradient - deltaX;
  19.  
  20.   if (abs(deltaY) < abs(deltaX))
  21.   {
  22.     if (mouseOldCordX > mouseNewCordX)
  23.     {
  24.       plotLineLow(mouseOldCordX, mouseOldCordY, deltaX, deltaY, gradient, error);
  25.     } else
  26.     {
  27.       plotLineLow(mouseNewCordX, mouseNewCordY, deltaX, deltaY, gradient, error);
  28.     }
  29.   } else
  30.   {
  31.     if (mouseOldCordY > mouseNewCordY)
  32.     {
  33.       plotLineHigh(mouseOldCordX, mouseOldCordY, deltaX, deltaY, gradient, error);
  34.     } else
  35.     {
  36.       plotLineHigh(mouseNewCordX, mouseNewCordY, deltaX, deltaY, gradient, error);
  37.     }
  38.   }
  39. }
  40.  
  41. void plotLineLow(int x0, int y0, int deltaX, int deltaY, int gradient, int error)
  42. {
  43.   int yIncrease = 1;
  44.  
  45.   if (deltaY < 0)
  46.   {
  47.     yIncrease = -1;
  48.     deltaY = -deltaY;
  49.   }
  50.  
  51.   for (int x = mouseOldCordX; x <= mouseNewCordX; x += 1)
  52.   {
  53.  
  54.     world[x][y0].state = selectedState;
  55.  
  56.     error += gradient;
  57.  
  58.     if (error >= 0)
  59.     {
  60.       y0 += yIncrease;
  61.       error -= (deltaX + deltaX);
  62.     }
  63.   }
  64. }
  65.  
  66. void plotLineHigh(int x0, int y0, int deltaX, int deltaY, int gradient, int error)
  67. {
  68.   int xIncrease = 1;
  69.  
  70.   if (deltaX < 0)
  71.   {
  72.     xIncrease = -1;
  73.     deltaX = -deltaX;
  74.   }
  75.  
  76.   for (int y = mouseOldCordY; y <= mouseNewCordY; y += 1)
  77.   {
  78.  
  79.     world[x0][y].state = selectedState;
  80.  
  81.     error += gradient;
  82.  
  83.     if (error >= 0)
  84.     {
  85.       x0 += xIncrease;
  86.       error -= (deltaY + deltaY);
  87.     }
  88.   }
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement