Search Unity

Draw line between 2 point in Texture2D

Discussion in 'Scripting' started by MikeyJY, Nov 20, 2021.

  1. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    I have 2 screen coordinates:
    Code (CSharp):
    1. Vector2Int origin;
    2. Vector2Int end;
    3. Texture2D img;
    4. Drawline(origin, end, Color.red, img);
    5.  
    6. private void DrawLine(Vector2Int origin, Vector2Int end, Color color, Texture2D targetTexture){
    7.             int diffX = (int)end.X - (int)origin.X;
    8.             int diffY = (int)end.Y - (int)origin.Y;
    9.             float error = 0;
    10.  
    11.             float diffError = Math.Abs((float)diffY / (float)diffX);
    12.            
    13.             int y = (int)origin.Y;
    14.             for (int x = (int)origin.X;x<endpoint.X;x++)
    15.             {
    16.                 print(x + " " + y);
    17.                 targetTexture.SetPixel(x, y, Color.Red);
    18.                 error = error + diffError;
    19.                 if (error >= 0.5)
    20.                 {
    21.                     ++y;
    22.                     error -= 1f;
    23.                 }
    24.             }
    25.             targetTexture.Apply();
    26. }
    I get an error saying that the Y from the SetPixel method is greater than the texture's height. The texture is 640x400 and the
    Vector2Int origin
    and
    Vector2Int end
    coordinates are not greater than the image, however the method I wrote generates some Y coordinates greater than 400.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,736
    Detect it and either a) clamp it (Mathf.Clamp()), or b) don't set it.
     
  3. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    I clamped it and it now works. Thanks!