Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating objects in actionscript 3?

I'm fairly new to AS3, and I've been trying to make a side scrolling shooter. I made some progress but I've hit a wall on the bullets themselves. The code I've been using 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 with this is it only allows for one bullet on the screen at a time. How can I change this so the bullets are created so that I can have an unlimited amount of them?

like image 231
user2034148 Avatar asked Feb 06 '26 02:02

user2034148


1 Answers

Create the object inside the 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 would only have one circle variable. This time, a new circle is created each time the method is called.

However, you will probably want to store all your circles somehow so that you can remove 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 your circles:

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

And to clear all circles:

for each (var circle: Sprite in allCircles) {
    removeChild(circle);
}
allCircles.clear();
like image 167
Simon Forsberg Avatar answered Feb 08 '26 03:02

Simon Forsberg