提高循环效率/可扩展性

发布于 2024-09-27 10:55:46 字数 557 浏览 1 评论 0原文

我有一个构成 2D 网格的像素数组,我想随着时间的推移左右移动这些像素......不断地,但是我想出的循环效率相当低,并且不允许在改变运动。任何关于如何改进我已有的想法将不胜感激。

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);
    }
  }
}

编辑:抱歉,代码中有错误,中间循环需要为-10,第一个for循环将所有像素向右移动,第二个循环将它们移回原点,然后向左移动,第三个循环然后将它们移回原点起源。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

向地狱狂奔 2024-10-04 10:55:46

您可以在实际使用像素的代码中使用偏移变量。然后通过更改偏移量来移动像素,这是一行代码。

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.

属性 2024-10-04 10:55:46

你不能只使用一个循环并使用 int 吗?三个循环似乎是多余的

使用从 0 到 x*2 的一个循环并执行选择 x 值的运动

类似

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)
     }       
}

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)
     }       
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文