如何在没有闪烁的情况下重绘2DTexture上的像素

时间:2015-12-02 19:56:16

标签: unity3d rendering

我想在2DTexture中画一条线。这在编辑器中很有效。但是,在编译的构建中,它会闪烁,因为它填充纹理的像素,然后重新绘制线条。

这是我的抽奖代码:

public void DrawLineWithMouse (Vector2 _middleVector)
{
    tex.SetPixels(fillPixels); // Fills texture with an array of clear pixels
    Vector3 newMousePos = Input.mousePosition;
    newMousePos.z = 0;
    int x0 = ((int)newMousePos.x)/RenderingManager.pixelSize  / thickness; //Screen.width-
    int y0 = ((int)newMousePos.y)/RenderingManager.pixelSize  / thickness; //Screen.height-
    int x1 =  (int)_middleVector.x - (x0 - (int)_middleVector.x );
    int y1 =  (int)_middleVector.y - (y0 - (int)_middleVector.y );
    DrawLineHelper(tex, x0, y0, x1, y1, Color.yellow); // redraws the line

    tex.Apply();
}

创建新纹理然后应用它时,我不会闪烁。但是,这非常非常昂贵且仅用于测试目的。

    public void DrawLineWithMouse (Vector2 _middleVector)
{
    tex = new Texture2D(Screen.width/RenderingManager.pixelSize / thickness, Screen.height/RenderingManager.pixelSize / thickness);
    tex.SetPixels(fillPixels);
    tex.SetPixels(fillPixels);
    tex.filterMode = FilterMode.Point;



    Vector3 newMousePos = Input.mousePosition;
    newMousePos.z = 0;
    int x0 = ((int)newMousePos.x)/RenderingManager.pixelSize  / thickness; //Screen.width-
    int y0 = ((int)newMousePos.y)/RenderingManager.pixelSize  / thickness; //Screen.height-
    int x1 =  (int)_middleVector.x - (x0 - (int)_middleVector.x );
    int y1 =  (int)_middleVector.y - (y0 - (int)_middleVector.y );
    DrawLineHelper(tex, x0, y0, x1, y1, Color.yellow);
    GetComponent<Renderer>().material.mainTexture = tex;

1 个答案:

答案 0 :(得分:0)

这是轻弹,因为申请是一项昂贵的操作。 The documentation州:

  

这是一项可能很昂贵的操作,因此您需要在Apply调用之间更改尽可能多的像素。

您必须找到一种方法来减少对DrawLineWithMouse的调用。什么是最好的解决方案,取决于你在做什么。

另一种方法是累积鼠标移动的增量并在 x 毫秒后绘制。另一种方法是在纹理顶部绘制一个网格而不是改变纹理,然后只在必要时更改纹理(如果有的话)(注意你可以在这里使用 RenderTexture 来轻松绘制网格)在纹理中。)

最后,降低纹理的分辨率会使Apply运行得更快。

相关问题