同时操作多个阵列

Operate multiple arrays simultaneously

我在 adobe animate 中使用 as3 创建视频游戏。 我用电影剪辑创建了多个数组,例如


var A:Array [mc1, mc2, mc3]
var B:Array [mc4, mc5, mc6]
var C:Array [mc7, mc8, mc9]
var anObject:DisplayObject;

如何同时操作所有数组中的所有影片剪辑? 我试过这个:


mc_Player.addEventListener(MouseEvent.CLICK, Change_Position);
function Change_Position (event:MouseEvent):void
{
    {for each (anObject in A) & (anObject in B) & (anObject in C) // how can I get this right?
    {anObject.x -= 100;
    }}
}

我也在尝试了解是否有一种方法可以在不使用数组的情况下同时操作我的项目中的所有影片剪辑。

例如

mc_Player.addEventListener(MouseEvent.CLICK, Change_Position);
function Change_Position (event:MouseEvent):void
{
    {all movie_clips // how can I get this right?
    {anObject.x -= 100;
    }}
}

谢谢。

在编程中没有同步这样的东西(好吧,除非你multi-threading完美同步,这根本不是AS3的故事)。

有很多方法可以接近同时的东西:

  1. 将所有 objects 放入一个容器中。您将能够更改该容器的 xy 因此所有 in-laid objects 都会更改其可见位置立刻。缺点是你不能单独旋转或缩放它们(将它们想象成夹在板上并想象你旋转整个板),否则你将无法移动它们的一半。
  2. Arrays 和循环。您非常快速地逐一遍历所有项目。从外面看起来同时,但它从来不是。

综上所述,为了实现您想要的事情,您需要想出一种方法将您想要同时处理的所有objects放入一个单一的数组然后对它们做你想做的事。

案例 №1:许多 数组 到一个。

// This methods takes a mixed list of items and Arrays
// and returns a single flattened list of items.
function flatten(...args:Array):Array
{
    var i:int = 0;

    // Iterate over the arguments from the first and on. 
    while (i < args.length)
    {
        if (args[i] is Array)
        {
            // These commands cut the reference to the Array
            // and put the whole list of its elements instead.
            aRay = [i,1].concat(args[i]);
            args.splice.apply(args, aRay);
        }
        else
        {
            // The element is not an Array so let's just leave it be.
            i++;
        }
    }

    return args;
}

然后您需要做的就是从多个 Arrays:

中获取一个列表
var ABC:Array = flatten(A, B, C);

for each (var anObject:DisplayObject in ABC)
{
    anObject.x -= 100;
}

Performance-wise,最好pre-organize,如果逻辑上可能的话,这些Arrays,这样你就不必分别编译它们了您需要处理所有 objects 的时间。简单地说,如果有时您需要 A + B,有时需要 B + C,有时需要 A + B + C,只需创建它们并准备好即可。如果你知道你要处理什么,你甚至不需要那种复杂的 flatten 方法:

var AB:Array = A.concat(B);
var BC:Array = B.concat(C);

var ABC:Array = A.concat(B).concat(C);

Case №2:一次全部children。正如我在 中解释的那样,您可以遍历某个容器的所有 children,并且您可以将它们放入 - 猜猜是什么 - Array 以备后用利用。此外,您可以在这样做时过滤 objects,只放置那些您真正想要的。

var ALL:Array = new Array;

// Iterate over the amount of children of "this" container.
for (var i:int = 0; i < numChildren; i++)
{
    // Obtain a reference to the child at the depth "i".
    var anObject:DisplayObject = getChildAt(i);

    // Here go possible criteria for enlisting.

    // This will ignore texts and buttons.
    // if (anObject is MovieClip)

    // This will take only those with names starting with "mc".
    if (anObject.name.substr(0, 2) == "mc")
    {
        ALL.push(anObject);
    }
}

// Viola! You have all the objects you want in a single Array
// so you can bulk-process them now, which is ALMOST simultaneous.