Copy link to clipboard
Copied
I am trying to make a game and I want to spawn 5 enemies when the game opens and place them in random places on the screen, but I can't figure it out.
The movieclip I am using is named Enemy and the linkage is named the exact same - Enemy
Here is what I have so far on the first frame::
var enemiesarray:Array;
enemiesarray = [];
function addEnemy():void
{
if(enemiesarray.length < 5)
{
var e:Enemy = new Enemy();
var startX:int = Math.random()*500-10; stage.stageWidth ;
var startY:int = Math.random()*500-10; stage.stageHeight ;
stage.addChild(e);
enemiesarray.push(e);
}
}
Besides of what Clay said, I want to point out that each of these two lines has an extra semicolon:
var startX:int = Math.random()*500-10; stage.stageWidth;
var startY:int = Math.random()*500-10; stage.stageHeight;
And your function will only generate one enemy if you don't call it more than once.
One suggestion to achieve what you want is like this:
...import flash.display.DisplayObjectContainer;
var enemies:Vector.<Enemy> = new Vector.<Enemy>();
// alternatively, you can write:
// var enemies:Array = [];
Copy link to clipboard
Copied
So you're instantiating a new instance of Enemy.
Then you're adding that instance to the stage.
Then you're also pushing a reference to that instance onto enemiesarray.
So why aren't you ever assigning to the .x or .y coordinates of your Enemy instance? If you're intending to write a game you surely already understand how to programmatically position clips on the stage.
Copy link to clipboard
Copied
Besides of what Clay said, I want to point out that each of these two lines has an extra semicolon:
var startX:int = Math.random()*500-10; stage.stageWidth;
var startY:int = Math.random()*500-10; stage.stageHeight;
And your function will only generate one enemy if you don't call it more than once.
One suggestion to achieve what you want is like this:
import flash.display.DisplayObjectContainer;
var enemies:Vector.<Enemy> = new Vector.<Enemy>();
// alternatively, you can write:
// var enemies:Array = [];
function addEnemies(container:DisplayObjectContainer, total:uint, minX:int, maxX:int, minY:int, maxY:int):void
{
for (var i:uint = 0; i < total; i++)
{
enemies = new Enemy();
enemies.x = Math.random() * (maxX - minX) + minX;
enemies.y = Math.random() * (maxY - minY) + minY;
container.addChild(enemies);
}
}
addEnemies(stage, 5, 0, stage.stageWidth, 0, stage.stageHeight);
I hope this helps.
Regards,
JC
Copy link to clipboard
Copied
You forgot to use the container parameter that's passed into that function.
Also, using enemies so many times instead of a local variable isn't great practice.
Copy link to clipboard
Copied
Fixed the container part. That was a last minute addition.