-1

I am still new to C#, but I hope that I can formulate my question understandably: With the following code I draw two random points on a texture with every mouse click in Unity. I would now like to connect these points with a line on every mouse click, no matter where the points are. I have already tried a few things and came across the Graphics.DrawLine() method. However, this does not work for me, which according to my research is most likely because the project is running and should continue to run on a Mac.

I hope you can help me with this problem and maybe have an idea how this can also work with macOS.

If there are any questions, feel free to ask me.

Thank you! Lara

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Texture2DEditor : MonoBehaviour
{
    Texture2D t2D;
    
    void Start()
    {   
        var rawImage = GetComponent<RawImage> ();
        t2D = rawImage.texture as Texture2D;
    }

    void Update()
    {   
        if (Input.GetMouseButtonDown(0))
                {
                        Vector2Int point1 = new Vector2Int(Random.Range(0,1072),Random.Range(0,1072));
            Vector2Int point2 = new Vector2Int(Random.Range(0,1072),Random.Range(0,1072));

            Vector2Int line = point2 - point1;

                        int x1 = (int) line.x; 
            int x2 = (int) line.x;
            int y1 = (int) line.y;
            int y2 = (int) line.y;

            t2D.SetPixel(x1,y1,new Color(255,255,255));
            t2D.SetPixel(x2,y2,new Color(255,255,255));
                    }
        t2D.Apply();
    }
}
Lara
  • 19
  • 4
  • 1
    I guess I would start at [Get all pixels between two points](https://stackoverflow.com/questions/13491676/get-all-pixel-coordinates-between-2-points/13491882) (it's in javascript but the concept stays the same in any language) – derHugo Jan 17 '22 at 19:58

1 Answers1

0

the following code should do the trick. just dont forget to t2D.Apply() After it's used.

public static void DrawLine(this texture2D t2D, Vector2 point1 , Vector2 point2, Color col)
{
    Vector2 t = point1 ;
    float frac = 1 / Mathf.Sqrt(Mathf.Pow(point2.x - point1.x, 2) + Mathf.Pow(point2.y - point1.y, 2));
    float ctr = 0;

    while ((int)t.x != (int)point2.x || (int)t.y != (int)point2.y)
    {
        t = Vector2.Lerp(point1 , point2, ctr);
        ctr += frac;
        t2D.SetPixel((int)t.x, (int)t.y, col);
    }
}
Pixel Paras
  • 169
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 18 '22 at 07:37