【问题标题】:Draw Line between two random Points on Texture | MacOS在纹理上的两个随机点之间画线 |苹果系统
【发布时间】:2022-01-18 15:26:40
【问题描述】:

我还是 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();
    }
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

下面的代码应该可以解决问题。 用完后别忘了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);
    }
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2012-03-27
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2016-08-25
  • 1970-01-01
相关资源
最近更新 更多