Dynamically creating objects in actionscript 3?

I'm new to AS3 and I was trying to make a side scrolling shooter. I made some progress, but I hit the wall with the bullets themselves. The code I used is:

var circle:Sprite = new Sprite();

function shoot() {
  circle.graphics.beginFill(0xFF794B);
  circle.graphics.drawCircle(0, 00, 7.5);
  circle.graphics.endFill();
  addChild(circle);
  circle.x = ship_mc.x;
  circle.y = ship_mc.y + 43; 
}

      

The problem is that it only allows one bullet per screen to be turned on at a time. How can I change this so that bullets are created so that I can have an unlimited number of them?

+3


source to share


2 answers


Create an object inside a method

function shoot() {
    var circle:Sprite = new Sprite();
    circle.graphics.beginFill(0xFF794B);
    circle.graphics.drawCircle(0, 00, 7.5);
    circle.graphics.endFill();
    addChild(circle);
    circle.x = ship_mc.x;
    circle.y = ship_mc.y + 43; 
}

      

Otherwise, you will only have one variable circle

. This time, a new circle is created every time the method is called.

However, you probably want to save all your circles in some way so that you can delete them later.

var allCircles: Vector.<Sprite> = new Vector.<Sprite>();
function shoot() {
    var circle:Sprite = new Sprite();
    circle.graphics.beginFill(0xFF794B);
    circle.graphics.drawCircle(0, 00, 7.5);
    circle.graphics.endFill();
    addChild(circle);
    circle.x = ship_mc.x;
    circle.y = ship_mc.y + 43; 
    allCircles.push(circle);
}

      



Then, at a later time, you can loop through all the circles:

for each (var circle: Sprite in allCircles) {
    // do something with this circle
}

      

And clear all circles:

for each (var circle: Sprite in allCircles) {
    removeChild(circle);
}
allCircles.clear();

      

+2


source


You want to store an array of Sprite

s, not just one of them. First, you declare your Array

:

var circles:Array = new Array(); 

      



Then you change the shooting function to create a new one and then paste it in Array

:

function shoot() {
    var circle:Sprite = new Sprite();

    circle.graphics.beginFill(0xFF794B);
    circle.graphics.drawCircle(0, 00, 7.5);
    circle.graphics.endFill();
    circle.x = ship_mc.x;
    circle.y = ship_mc.y + 43; 

    circles.push(circle);  
    addChild(circles[circles.length-1]);
}

      

0


source







All Articles