Welcome to WebmasterWorld Guest from 54.166.178.177

Forum Moderators: open

Message Too Old, No Replies

AS3 dynamic sprite name

     
7:41 pm on Jul 24, 2009 (gmt 0)

5+ Year Member



When creating a sprite object using var point2:Sprite = new Sprite();

Apparently I'm not allowed to use a dynamic variable name so how would I create a series of sprites in a while loop?

8:52 pm on Jul 24, 2009 (gmt 0)

5+ Year Member



I appear to of got some of the way there but don't understand why the line
sprite_1.width=400; causes a problem, how would I refer to each individual sprite?

var i:Number=0;
var n:Number=7;
while( i < n )
{
// Create the Sprite
var sprite:Sprite = new Sprite();
sprite.graphics.beginFill( 0 );
sprite.graphics.drawRect( 0, 0, 50, 50 );
sprite.graphics.endFill();
sprite.x = Math.random() * 500;
sprite.y = Math.random() * 300;

sprite.buttonMode = true;
sprite.mouseChildren = false;

// Give the Sprite a name
sprite.name = "sprite_" + i; // "sprite_0" "sprite_1" ...

// Get a reference to an event listener
var type:String = "MouseDown";
var listener:Function = this[ "on" + type ]; // "onMouseDown"

// Add the listener to the sprite.
sprite.addEventListener( MouseEvent.MOUSE_DOWN, listener );

// Add the sprite to the display list.
addChild( sprite );

// Increase the loop counter.
i ++;
}

function onMouseDown( e:MouseEvent ):void
{
var sprite:Sprite = Sprite( e.target );
trace( sprite.name ); // "sprite_0" "sprite_1" .
sprite_1.width=400;
}

9:37 am on Jul 28, 2009 (gmt 0)

5+ Year Member



Solved this now, see below.

var i:Number=0;
var n:Number=7;
var squaresArray:Array = new Array();
while( i < n )
{
// Create the Sprite
var sprite:Sprite = new Sprite();
sprite.graphics.beginFill( 0 );
sprite.graphics.drawRect( 0, 0, 50, 50 );
sprite.graphics.endFill();
sprite.x = Math.random() * 500;
sprite.y = Math.random() * 300;

sprite.buttonMode = true;
sprite.mouseChildren = false;

// Give the Sprite a name
sprite.name = "sprite_" + i; // "sprite_0" "sprite_1" ...

// Add the listener to the sprite.
sprite.addEventListener( MouseEvent.MOUSE_DOWN, Squash );

// Add the sprite to the display list.
addChild( sprite );

squaresArray.push(sprite);

// Increase the loop counter.
i ++;
}

function Squash( e:MouseEvent ):void
{

e.target.width=10;
squaresArray[0].height=10;
}

 

Featured Threads

Hot Threads This Week

Hot Threads This Month