[英]Draw Line between two random Points on Texture | MacOS
我仍然是 C# 的新手,但我希望我可以理解地提出我的問題:使用以下代碼,我在 Unity 中每次單擊鼠標時都會在紋理上繪制兩個隨機點。 我現在想在每次鼠標點擊時用一條線連接這些點,無論這些點在哪里。 我已經嘗試了一些事情並遇到了 Graphics.DrawLine() 方法。 但是,這對我不起作用,根據我的研究,這很可能是因為該項目正在運行並且應該繼續在 Mac 上運行。
我希望你能幫助我解決這個問題,也許知道這也適用於 macOS。
如果有任何問題,請隨時問我。
謝謝! 勞拉
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();
}
}
下面的代碼應該可以解決問題。 只是不要忘記在t2D.Apply()
使用后。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.