views:

53

answers:

2

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 loop then moves them back to the origin.

A: 

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)
     }       
}
il_guru
+1  A: 

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.

Dialecticus
Great idea thanks (Y)
philbert