开发者

Improving loop efficiency/extensibility

I have an array of pixels which make up a 2D grid and I want to move these pixels right and left over time... constantly however the loop I came up with is fairly inefficient and does not allow for much expansion in terms of changing the motion. Any ideas on how to improve what I already have would be much appreciated.

while (true)
{
  for (float i = 0; i < x; i++)
  {
    foreach (Pixel p in pixels)
    {
      p.move(10, 0);
    }
  }
  for (float i = 0; i < x * 2; i++)
  {
    foreach (Pixel p in pixels)
    {
      p.move(-10, 0);
    }
  }
  for (float i = 0; i < x; i++)
  {
    foreach (Pixel p in pixels)
    {
      p.move(10, 0);
    }
  }
}

Edit: Sorry had an error in the code the middle loop needed to be -10 the first for loop moves all the pixels right, the second moves them back to the origin and then to the left, the third lo开发者_高级运维op then moves them back to the origin.


You could employ an offset variable to be used in the code where pixels are actually used. Moving pixels around is then done by changing offset, which is one line of code.


Can't you just use a single loop and using int? Three loops seems to be redundant

Use one loop from 0 to x*2 and perform the movement choosing on the x value

Something like

for(int i = 0; i < x * 2; i++)
{
    foreach(Pixel p in pixels)
    {
        if (i < x)
        {
            p.move(0.1, 0);
            p.move(10, 0);
            p.move(10, 0);
        }
        else
            p.move(10,0)
     }       
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜