Spawn Enemies in ActionScript 3.0 - actionscript-3

Something is going wrong in my mind, In my game , I want to instantiate enemies within library and put them on stage. so I create an EnemySpawner class and I put an instance from that class onto the stage . ( drag drop from library and give it a instance name). So here is the code for EnemySpawner class:
package scripts {
import flash.display.MovieClip;
public class EnemySpawner extends MovieClip {
var positions: Array = new Array(); // clockwise spawn positions
var enemies : Array = new Array();
var spwan:Boolean=false;
public function EnemySpawner() {
positions.push(MovieClip(root).rightPos);
positions.push(MovieClip(root).leftPos);
enemies.push("Enemy1");// here is the problem
}
public function tick(): void {
}
public function doSpwan():void{
}
}
}
So the problem issues here is , I want to randomly load enemies from library and instance them on stage , the design environment is something like this :
There are diffrent enemy movieclips in library with same blass class:
I don't want to assign each enemy a new class , for example I don't want to assign EnemyA Class to Enemy1 MovieClip Object and EnemyB Class to Enemy2 MovieClip . I want All Enemy MovieClip in the library share same class Enemy. so but using this , instantiate is hard task, I don't know how to instantiate enemies by using this method?
I know if I have separate class for each Enemy I can do this:
var e1 : Enemy1 = new Enemy1();
var e2 : Enemy2 = new Enemy2();
...
var e3 : Enemy3 = new Enemy3();
But I want do something like this:
//Pseudocode:
//Instantiate form library (Name Of Enemy1); //base class is enemy 1
//Instantiate form library (Name Of Enemy1); //base class is enemy 1
//Instantiate form library (Name Of Enemy1); //base class is enemy 1
Thanks in advance.

It's an easy task, actually. Assign enemies with different classes, then
// List classes in this Array.
var Enemies:Array = [Enemy1, Enemy2, Enemy3];
// Get a random class from the list.
var anIndex:int = Math.random() * Enemies.length;
var EnemyClass:Class = Enemies[anIndex];
// Spawn a random enemy.
// You can have a common superclass, or just use MovieClip or Sprite they are subclassed from.
var anEnemy:MovieClip = new EnemyClass;

Related

Addchild - object not appearing on stage from external class

I'm having problem with "DiamondEnemy" objects created in external class "Level" not appearing on the stage. I'm trying to retrieve a random enemy from "EnemyNotReleasedArray" at intervals and add them to screen through "enemyOnScreen" sprite.
Please note I have not 100% finished with all the functionality; so it may seem a little weird. I don't want to go further until I can actually get it working.
update: I create a new "level" object from a separate document class called "main".
package {
import DiamondEnemy;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.Sprite;
import flash.display.MovieClip;
public class Level extends MovieClip {
private const START_DELAY_SECONDS:uint = 1000;
private var EnemyNotReleasedArray:Array = new Array();
private var startDelay:Timer;
private var enemyOnScreen: Sprite;
public function Level(NumberDiamonds:uint)
{
// load the required enemies into the array
loadEnemyArray(NumberDiamonds);
//setup up sprite, for enemies that will appear on the screen
enemyOnScreen = new Sprite();
addChildAt(enemyOnScreen, numChildren);
// create delay timer before enemies can start appearing on screen
startDelay = new Timer(START_DELAY_SECONDS,1);
// set eventlistener that once delay finishes
startDelay.addEventListener(TimerEvent.TIMER_COMPLETE, releaseRandomEnemy);
startDelay.start();
//setup up sprite, for enemies that will appear on the screen
enemyOnScreen = new Sprite();
addChild(enemyOnScreen);
}
// creates the requested number of enemies type into EnemyNotReleasedArray so they can be released later
private function loadEnemyArray(numDiamonds:uint)
{
// use requested number diamonds enemies - to create diamond enemy objects
for (var i:uint = 0; i < numDiamonds; i++)
{
var diamond:DiamondEnemy = new DiamondEnemy();
EnemyNotReleasedArray.push(diamond);
}
}
// selects a random enemy from EnemyNotReleasedArray and resizes the array so enemy is no longer in it
private function releaseRandomEnemy(evt:TimerEvent)
{
var arrayLength:uint = EnemyNotReleasedArray.length;
// check make sure array is not empty, if empy level is over
if (arrayLength > 0)
{
var randomArrayIndex = Math.ceil(Math.random() * arrayLength) -1;
/// adding random enemy to sprite object
enemyOnScreen.addChild(EnemyNotReleasedArray[randomArrayIndex]);
trace(EnemyNotReleasedArray[randomArrayIndex]);
//remove the enemy from array and make element null
EnemyNotReleasedArray.removeAt(randomArrayIndex)
//tempory array to store non-null values
var tempArray:Array = new Array();
// cycle through EnemyNotReleasedArray and store all values that are not null into temp array
for each(var enemy in EnemyNotReleasedArray)
{
if (enemy != null)
{
tempArray.push(enemy)
}
}
// save temp array value into EnemyNotReleasedArray
EnemyNotReleasedArray = tempArray;
}
else
{
trace("no more enemies left in array");
}
}
}
}
document class "Main":
package {
import Level;
import DiamondEnemy;
import flash.display.MovieClip;
public class Main extends MovieClip
{
public function Main()
{
var level:Level = new Level(1);
}
}
}
The display list is a hierarchical graph, often called a tree.
Everything that's directly or indirectly connected to the root node is displayed. The root node is the Stage object. While possible, nothing of your own code should actually addChild() to this object. (for reasons out of the scope of this answer)
The only child of the Stage is the instance of your document class that's created when your .swf file is executed. This instance is automatically added to the Stage object, too, which is why you never have to add the document class to anything but it's still visible.
The constructor of your Main class looks like this:
public function Main()
{
var level:Level = new Level(1);
}
The problem is that while you successfully create the Level object, it is never added to the above described hierarchy that's usually called the "display list". level is not connected to the root node, which is why it is not displayed. You can still add children to level, but they won't be visible either for the same reason: that is, level is not visible.
To fix this, add level to your document class like so:
public function Main()
{
var level:Level = new Level(1);
addChild(level);
}
Btw. you have this code twice:
//setup up sprite, for enemies that will appear on the screen
enemyOnScreen = new Sprite();
addChildAt(enemyOnScreen, numChildren);
and
//setup up sprite, for enemies that will appear on the screen
enemyOnScreen = new Sprite();
addChild(enemyOnScreen);
but you only need it once. The second one is all you need.
And neither one of your two classes should extends MovieClip as non of them have a time line. Use extends Sprite unless you are actually dealing with MovieClips.

Referring to a variable in the target file from a class AS3

I've researched this all day and I'm stuck! I want to know how to use a variable from a target path to move something. Here is the code:
// Target file
var speed:int = Number(1);
var container:MovieClip = new MovieClip;
var objects:Objects = new Objects();
container.addChild(objects);
and
// Class for Objects
package {
import flash.display.MovieClip;
public class Objects extends MovieClip {
public function Objects() {
this.x += speed;
trace(this.x);
}
}
}
When I run it, I get an error like this:
Objects.as, Line 6 1120: Access of undefined property speed.
Thanks!
The most simple way to do it is to pass the speed variable to that class. See, classes are like stand alone objects in the space, and they (mostly) don't know about each other, or at least they don't know about the variables that you define in them.
So if you create a class inside another one (new Objects()), the most easy way is this:
var objects:Objects = new Objects(speed);
Then, inside Objects class, you will have:
public class Objects extends MovieClip {
var _speed:Number;
public function Objects(speed:Number) {
_speed = speed; // save it to a local member variable
this.x += _speed;
// start working with the local one,
// which will be accessible in the whole class
}
It's like passing some defined values, so that class can use them. And the class saves them inside itself so it can be used through the whole file (scope).

want to change the code actionscript2 to actionscript3?

i am newbie to flash.i need to change the below actionscript code to actionscript 3.0 code.
i am currently working on drag and drop. so i want to duplicate the movieclip while dragging i found the code on internet but it is actionscript 2.0 so please convert it to as3. the box is a instance name of a movieclip.
the code blocks are:
var num:Number = 0
box.onPress = function(){
num++
duplicateMovieClip(box ,"box"+num, _root.getNextHighestDepth())
_root["box"+num].startDrag();
}
box.onReleaseOutside = function(){
trace(_root["box"+num])
stopDrag();
}
If you dont want to use seperate .as file, follow this steps:
1- assign AS linkage to box movieClip (in library panel):
2- Select frame 1 on the timeline, and paste this code in the Actions panel:
var boxes:Array=[];
//var box:Box=new Box();
//addChild(box);
box.addEventListener(MouseEvent.MOUSE_DOWN,generateBox);
function generateBox(e:MouseEvent):void{
var newBox:Box=new Box();
newBox.x = e.target.x;
newBox.y = e.target.y;
newBox.startDrag();
newBox.addEventListener(MouseEvent.MOUSE_UP,stopD);
newBox.addEventListener(MouseEvent.MOUSE_DOWN,startD);
boxes.push(newBox);
addChild(newBox);
}
function startD(e:MouseEvent):void{
e.target.startDrag();
}
function stopD(e:MouseEvent):void{
e.target.stopDrag();
}
Unfortunately, there's no duplicateMovieClip analog in AS3, so you'll have to create a Class for your box movieClip template. Let's say it will be called BoxTemplate. (You can google how to create Classes for your library object). Add a Class with this name and add this code (event subscription in the constructor and a private event listener). You'll get something like this:
package
{
public class BoxTemplate
{
public function BoxTemplate()
{
addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
}
private function onMouseUp(e:MouseEvent):void
{
stopDrag();
}
}
Leave your present instance of this symbol on the stage. This is your code in the frame:
import flash.event.MouseEvent
box.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent):void
{
var newBox:BoxTemplate = new BoxTemplate();
newBox.x = e.target.x;
newBox.y = e.target.y;
addChild(newBox);
newBox.startDrag();
}
It will allow you to infinitely clone your boxes. Of course, you can add all of them in the array to keep the references.

How to convert a Shape to MovieClip using ActionScript 3.0 only

import flash.display.Shape;
import flash.display.Graphics;
stage.addEventListener(Event.ENTER_FRAME, startAnim);
function startAnim(e:Event):void
{
var shape1:Shape = new Shape();
shape1.graphics.beginFill(0x333333,1);
shape1.graphics.drawRect(40,50,250,125);
shape1.graphics.endFill();
addChild(shape1); // this will add a shape of rectangle to stage
}
This is a very simple function creating a rectangle shape on stage. Ok but the problem is how can I convert this SHAPE to MOVIECLIP using ActionScript only so I can add Events to the same (shape1).
hmmm by using a MovieClip instead of a Shape. a MovieClip also has a Graphics object.
import flash.display.MovieClip ;
//import flash.display.Graphics;//not needed
//stage.addEventListener(Event.ENTER_FRAME, startAnim); //remove enterframe
//function startAnim(e:Event):void { //no need for a handler
var shape1:MovieClip = new MovieClip();
shape1.graphics.beginFill(0x333333,1);
shape1.graphics.drawRect(40,50,250,125);
shape1.graphics.endFill();
addChild(shape1); // this will add a MovieClip of rectangle to stage
shape1.addEventListener(MouseEvent.MOUSE_DOWN, dragShape);
function dragShape(E:MouseEvent)
{
shape1.startDrag()
}
shape1.addEventListener(MouseEvent.MOUSE_UP, dropShape);
function dropShape(E:MouseEvent)
{
shape1.stopDrag()
}
//} no need for that either :)
beware that, as such, your function is called on ENTER_FRAME = 25 or more times per second, therefore you'll create and add a clip to stage 25 or more times per second
+ the reference is created locally, in the function, so you won't be able to access "shape1" from outside, once your object is created.
I don't think you can convert a Shape to a MovieClip. What you can do is to create a MovieClip class, and in the constructor generate the Shape object, and add it to the MovieClip.
public class Car extends MovieClip {
private var shape1:Shape = new Shape();
public function Car() {
shape1.graphics.beginFill(0x333333,1);
shape1.graphics.drawRect(40,50,250,125);
shape1.graphics.endFill();
addChild(shape1); // this will add a shape of rectangle to stage
}
}
Shape has also events.
activate
added
addedToStage
deactivate
enterFrame
removed
removedFromStage
render
But since it doesn't extends from InteractiveObject, you can't handle input.

how do I access the main class's stage? + Can I pass functions as arguments like this?

There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as
TestAPP.as:
package {
import flash.display.Sprite;
import flash.display.Stage;
public class TestAPP extends Sprite
{
var _mainStage:Stage;
public function TestAPP()//This is where we test the UI components.
{
var sp:Sprite = new Sprite();
_mainStage = stage;
_mainStage.addChild(sp);
sp.graphics.beginFill(0x00FF00);
sp.graphics.drawCircle(0,0,10);
sp.graphics.endFill();
sp.x = 50;
sp.y = 50;
var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
}
public function limitingfunc(x:Number,y:Number):int{
return 0;
}
}
}
And for the draggable.as:
package
{
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.MouseEvent;
public class Draggable
{
private var _limitingFunc:Function;
private var _which:Sprite;
private var _MouseSavedX:Number;
private var _MouseSavedY:Number;
private var _stage:Stage;
public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
{
_limitingFunc = limitingfunc;
_which = which;
_stage = stage;
_which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);
}
//limiting func: returns 0 when the object is free to move that place.
//returns -1 when the user wants to block X coordinate changes (but maintain Y free)
//returns -2 when the user wants to block Y ...
//returns -3 or less when the user wants to block both X and Y from changing.
//returns
private function Return_0(x:Number = 0,y:Number = 0):int{
return 0;
}
private function begin_drag(ev:MouseEvent):void{
var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
if(limitingFuncReturnValue == 0){//free to move.
_which.x = xTo;
_which.y = yTo;
}
else if(limitingFuncReturnValue == -1){//free to move Y
_which.y = yTo;
}
else if(limitingFuncReturnValue == -2){
_which.y = yTo;
}
//else:do nothing.
}
}
}
In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(
...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.
Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!
You're implementing your 2nd class as "draggable", when you named it (and it has to be named) "Draggable" with an upper case. Change it and see if that works. You seem to be passing in the parent classes stage correctly though.
If TestAPP is your document class. You can access to the stage thru the stage property (like your are doing in your example).
If TestAPP is not the document class, you should listen first to the ADDED_TO_STAGE event and then access to the stage property.
There is no need to add _mainStage property because you already have the stage property.
In order to move objects around, you need to use the ENTER_FRAME event.
You can access the main class' stage property the same way you do it for any DisplayObject on the stage: Use this.stage.
So just this should be enough:
var sp:Sprite = new Sprite();
stage.addChild(sp);
You could then pass the sprite and the main class' stage as a parameter, the way you did - but I would recommend creating a subclass Draggable extends Sprite and instantiate the whole thing using new Draggable() instead.
The new object will automatically have its own reference to stage as soon as it is added to the display list, and limitingFunc could be a member of Draggable, as well.
Also, you can use the startDrag() and stopDrag() methods, no need to implement your own: You can specify a Rectangle as a parameter to startDrag() to limit the permitted movement.
if you need it so much you may:
private static var _instance: TestAPP;
//...
public function TestAPP(){
_instance = this;
//...
}
public static function get instance():TestAPP{
return _instance;
}
public static function set instance(newVal: TestAPP):void{
_instance = newVal;
}
and you'll be able to reference its stage from any class where your TestAPP will be imported just with TestAPP.instance.stage.
but _instance is a property of the class TestAPP itself, not its instances