代码之家  ›  专栏  ›  技术社区  ›  StuckInPhDNoMore

如何在画布上自上而下画一条线?

  •  0
  • StuckInPhDNoMore  · 技术社区  · 7 年前

    我想在我的游戏中添加一条分割左右区域的线。我在画布中添加了一个游戏对象,并添加了以下脚本:

    public class DrawLine : MonoBehaviour
    {
        public Color c1 = Color.red;
        public Color c2 = Color.white;
        Vector3 topPoint;
        Vector3 bottomPoint;
    
        // Start is called before the first frame update
        void Start()
        {
            topPoint = new Vector3(Screen.width / 4, Screen.height);
            bottomPoint = new Vector3(Screen.width / 4, 0);
            LineRenderer lineRenderer = gameObject.AddComponent<LineRenderer>();
            lineRenderer.material = new Material(Shader.Find("Sprites/Default"));
            lineRenderer.widthMultiplier = 2.2f;
            lineRenderer.positionCount = 40;
    
            // A simple 2 color gradient with a fixed alpha of 1.0f.
            float alpha = 1.0f;
            Gradient gradient = new Gradient();
            gradient.SetKeys(
                new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) },
                new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
            );
            lineRenderer.colorGradient = gradient;
    
            lineRenderer.SetPosition(0, topPoint);
            lineRenderer.SetPosition(1, bottomPoint);
        }
    
    
    }
    

    当我比赛的时候。线条渲染器以所需的颜色和宽度添加到游戏对象中,但没有绘制线条。

    我做错什么了?

    enter image description here

    谢谢

    enter image description here

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Eissa    7 年前

    刚刚测试了你发布的代码,运行良好。我最初认为这条线被画得太细了,所以建议在开始和结束点调整线的大小,使其更大,但是测试之后,我确实看到了在编辑器和游戏中画的线。

    Here's an image of it being drawn in engine

    如果 LineRenderer 正在创建组件,您无法看到行编辑器或游戏视图,然后发布具有 衬线机 组件在运行时。


    对你的评论的回应

    使用linerenderer在运行时在三维空间中根据在代码中选择的位置绘制一条线。 SetPosition 电话。

    当谈论一个 Canvas 我想你是在说 UI画布 .

    linerenderer根据您设置的位置绘制,而不是根据画布绘制,除非您以这种方式编程。

    因此,如果您的相机没有定位在可以看到它前面的行的位置,那么它将不会显示在 game view .

    Here's an image show how I have my camera set up to see the line