我正在尝试制作橡皮擦工具(当用户在纹理上拖动手指时,纹理在该位置变得透明)。我尝试使用下面的代码(我在网上找到了一个例子并稍微修改了一下),但它太慢了。我正在使用画笔纹理在背景纹理上绘制..是否有另一个解决此问题的方法?也许使用一些着色器会更快但我不知道如何。
感谢您的帮助
void Start()
{
stencilUV = new Color[stencil.width * stencil.height];
tex = (Texture2D)Instantiate(paintMaterial.mainTexture);
}
void Update ()
{
RaycastHit hit;
if (Input.touchCount == 0) return;
//if (!Input.GetMouseButton(0)) return;
if (Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), out hit))
{
pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
CreateStencil((int)pixelUV.x, (int)pixelUV.y, stencil);
}
}
void CreateStencil(int x, int y, Texture2D texture)
{
paintMaterial.mainTexture = tex;
for (int xPix = 0; xPix<texture.width; xPix++)
{
for (int yPix=0;yPix<texture.height; yPix++)
{
stencilUV[i] = tex.GetPixel((x - texture.width / 2) + xPix,
(y - texture.height / 2) + yPix);
stencilUV[i].a = 0;//1-color.a;
i++;
}
}
i=0;
tex.SetPixels(x-texture.width/2, y-texture.height/2, texture.width, texture.height, stencilUV);
tex.Apply();
}
答案 0 :(得分:2)
你知道,每一帧都会调用Update()
函数。因此,您应该尝试优化代码。 CreateStencil()
函数对我来说似乎相当昂贵,因为迭代纹理中的每个像素然后在for循环中调用tex.GetPixel(..)
- 这意味着:
当你触摸屏幕时,应用程序会尝试为纹理中的每个像素运行此功能的每一帧 - 绝对不是要走的路。
我会尝试缓冲Start()
或Awake()
函数中某些其他数组中的像素信息,并仅在Update()
中执行必要的部分。您可以省去所有昂贵的操作,这对于让您的应用在iPhone上顺利运行至关重要。