使红线内的所有内容都变红

时间:2014-04-02 09:00:19

标签: c# unity3d pixels

我的统一堆栈溢出错误。 这将使红线内的每一个都变红。有办法解决这个问题吗?还是有更好的方法让红线上的所有东西变红?

void Checkpoint(Texture2D tex, int x, int y){

    if (tex.GetPixel(x,tex.height-y).r == 1) return;

    tex.SetPixel(x,tex.height-y,Color.red);

    Checkpoint(tex,x+1,y);
    Checkpoint(tex,x,y+1);
    Checkpoint(tex,x-1,y);
    Checkpoint(tex,x,y-1);

    return;
}

我想让红线内的所有东西变红 enter image description here

2 个答案:

答案 0 :(得分:0)

这可能是以下三件事中的一件或多件:

1 - 与int 1的float比较总是返回false。使用Mathf.Approximately

if (Mathf.Approximately(tex.GetPixel(x,tex.height-y).r, 1f) return;

2 - 您没有测试纹理的限制,因此xy会增长到 + infinity -infinity ,因为超出限制的GetPixel不会返回任何红色:)

3 - 堆栈内存是一种有限的资源,如果你有一个很大的纹理,堆栈将不足以堆叠如此多的方法调用。请改用System.Collections.Generic.Stack<>

我可以问你为什么要在Unity中实现泛洪填充算法?

答案 1 :(得分:0)

我找到了方法。 这是我的系列

void Stack(int x, int y, Texture2D tex){

    //make a list and add the first pixel 
    List<PT> toDo = new List<PT>();
    toDo.Add(new PT(x,y,state));

    while(toDo.Count != 0){

        PT thisPoint = toDo[toDo.Count-1];

        switch(thisPoint.State){
            case 0:

                //remove this pixel from the list when he is red
                if (tex.GetPixel(thisPoint.X,tex.height-thisPoint.Y).r == 1f) {
                    toDo.RemoveAt(toDo.Count-1);
                }else{

                    //change state and add the right pixel
                    tex.SetPixel(thisPoint.X,tex.height-thisPoint.Y,new Color(1,0,0));
                    toDo[toDo.Count-1].State = 1;
                    toDo.Add(new PT(thisPoint.X+1,thisPoint.Y,0));
                }
            break;

            //add the pixel below this one
            case 1:
                toDo[toDo.Count-1].State = 2;
                toDo.Add(new PT(thisPoint.X,thisPoint.Y+1,0));
            break;

            //add left pixel
            case 2:
                toDo[toDo.Count-1].State = 3;
                toDo.Add(new PT(thisPoint.X-1,thisPoint.Y,0));
            break;

            //add the last pixel and remove himself
            case 3:
                toDo.RemoveAt(toDo.Count-1);
                toDo.Add(new PT(thisPoint.X,thisPoint.Y-1,0));
            break;
        }
    }
}