PDA

View Full Version : array of data objects: please explain



tpann
November 29th, 2007, 12:20 PM
I'm playing around with the Asteroids game knock-off in Rosenzweig's "ActionScript 3.0 Game Programming University" and I've run into something that Rosenzweig does not explain well and that I do not understand.

As he creates the single class that runs the asteroids-like game, he comes to the part where he creates the "rocks" and adds them to the stage. The rocks are movieclips in the Library, three different sizes (radiuses), are invoked as "newRock" and, since there are multiple rocks, put in the "rocks" array.

Here's what I need help with: For the following line of code, Rosenzweig gives the following explanation [dx, dy, and dr are references to translation and rotation]:

"The rocks array is made up of data objects that include a reference to the rock movie clip, the dx, dy, and dr values, the rockType (size) and the rockRadius."

Here's the code:



rocks.push({rock:newRock, dx:dx, dy:dy, dr:dr,
rockType:rockType, rockRadius:rockRadius});


I need help understanding what that line of code does. The curly braces and colon-separated arguments are not something I've seen before.

Thanks!

Charleh
November 29th, 2007, 12:39 PM
They are just an array specifier and array key specifiers ... usually you will add single objects to an array using

array.push(object);

or

array[index] = object;

but you can also use strings as keys

array[key(as a string)] = object;

array["xposition"] = 5;

and you can also add arrays to arrays using {}

// No keys
array.push({1,2,3});
// with keys
array.push({key1:1,key2:2,key3:3});

The {} mean that you are pushing a list of values onto the array (another array really) and specifying keys with :

rock is the key newRock is the object you are adding

dx is the key and dx happens to also be the name of the variable you are adding

and so on!

So this array is now 2 dimensional!

i.e.

trace(rocks[0]["dx"]);

Personally that approach is one that I wouldn't use...

I'd just create a class for the rocks and push an instance of the class onto the array, but different strokes...etc!