Search code examples
actionscript-3flashmovieclip

Add a new instance of movie clip each time I click


I'm trying to create a movie clip every time I click the stage. I know that addChild does not add new instances, so every time I click, the previous cube disappears. I tried using an array to create multiple movie clips with no success. I'm pretty new to ActionScript, so I'm sorry for this naive question.

stage.addEventListener(MouseEvent.CLICK, spawnCube);

var i:int = 0;
var p1:cube = new cube();

function spawnCube(event:MouseEvent):void
{
p1.name = "p1";
p1.x = mouseX;
p1.y = mouseY;

arr.push(p1);
addChild(arr[i]);
i++;
}

Solution

  • Place new Cube() call into your click handler, this way it'll create a new cube properly.

    function spawnCube(event:MouseEvent):void
    {
         var p1:Cube=new Cube(); // this
         p1.x = mouseX;
         p1.y = mouseY;
         arr.push(p1);
         addChild(p1); // also this, because now "p1" has a new cube each time
         i++;
     }