How to make MC buttons with click actions from an Object Array and organize them into a grid.
I couldn’t find a simple example of how to do this with AS3 so I made one to share. Please let me know if there is a better way to do this.
Paste This Into A Flash Frame
var tX:Number = 0;
var tY:Number = 0;
var tWidth:Number = 100;
var tHeight:Number = 100;
var tSpacing:Number = 5;
var tAmountThumbsWide:Number = 3;
var _items:Array = new Array();
_items.push ({thumb:"3d_game_.jpg", full:"3d_game.jpg"});
_items.push ({thumb:"bottega_contact_.jpg", full:"bottega_contact.jpg"});
_items.push ({thumb:"bottega_events_.jpg", full:"bottega_events.jpg"});
_items.push ({thumb:"bottega_winelist_.jpg", full:"bottega_winelist.jpg"});
_items.push ({thumb:"circa_cocktails_.jpg", full:"circa_cocktails.jpg"});
_items.push ({thumb:"3d_game_.jpg", full:"3d_game.jpg"});
_items.push ({thumb:"bottega_contact_.jpg", full:"bottega_contact.jpg"});
_items.push ({thumb:"bottega_events_.jpg", full:"bottega_events.jpg"});
_items.push ({thumb:"bottega_winelist_.jpg", full:"bottega_winelist.jpg"});
_items.push ({thumb:"circa_cocktails_.jpg", full:"circa_cocktails.jpg"});
/////////////////////////////////////////////////////////////////////////////////
for (var i = 0; i<_items.length; i++) {
createButton (tWidth, tHeight, "btn"+String(i), i);
}
function createButton (w:Number, h:Number, nam:String, i:Number):void {
//---------------------------------- create an MC
this.nam = new MovieClip();
//---------------------------------- create a thumb backing
var sh:Shape = new Shape();
sh.graphics.beginFill (0x333333,1);
sh.graphics.drawRect (0, 0, w, h);
sh.graphics.endFill ();
//---------------------------------- stick thumb backing into the MC
this.nam.addChild (sh);
//---------------------------------- Layout this MC on a grid
if(i%tAmountThumbsWide==0 && i != 0){
tY+=(h+tSpacing);
}
this.nam.x = ((i%tAmountThumbsWide)*(w+tSpacing));
this.nam.y = tY;
//---------------------------------- Add vars to MC
this.nam.name = nam;
this.nam.thumb = _items*.thumb;
this.nam.full = _items*.full;
//---------------------------------- Give MC cursor
this.nam.buttonMode = true;
//---------------------------------- Add MC to whatever MC "this" is
addChildAt (this.nam, 0);
//---------------------------------- Add MC to current position
this.nam.addEventListener (MouseEvent.MOUSE_DOWN, clicked);
this.nam.addEventListener (MouseEvent.MOUSE_OVER, over);
this.nam.addEventListener (MouseEvent.MOUSE_OUT, out);
}
function clicked (e:MouseEvent):void {
trace (" ");
trace ("btns name: ", e.target.name);
trace ("btns parents name: ", e.target.parent.name);
trace ("thumb: ", e.target.thumb);
trace ("full: ", e.target.full);
}
function over (e:MouseEvent):void {
e.target.alpha=0.5;
}
function out (e:MouseEvent):void {
e.target.alpha=1;
}