add two enemy in one array AS3 - actionscript-3

i want add two enemy an one array for looping, this my code
global_time++;
// generate enemies
if (global_time % 40 == 0) {
enemy = new Enemy();
enemy.x = 40 + Math.random() * 400;
enemy.y = 0;
addChild(enemy);
army.push(enemy);
System.gc();
enemy2 = new Enemy2();
enemy2.x = 40 + Math.random() * 400;
enemy2.y = 0;
addChild(enemy2);
army.push(enemy2);
}
for (var k:int = army.length - 1; k >= 0; k--) {
enemy = army[k];
enemy2 = army[k]
// update all enemies
enemy.update();
enemy2.update2();
// if its out of bound, remove from stage
if (enemy.y < 0) {
army.splice(k, 1);
enemy.parent.removeChild(enemy);
continue;
System.gc();
}
//* enemy2
if (enemy2.y < 0) {
army.splice(k, 1);
enemy2.parent.removeChild(enemy2);
continue;
System.gc();
}
}
when i run this program error "cannot convert Enemy2#501f5e1 to Enemy". please help

The problem is that you have an army with enemies of two different types, Enemy and Enemy2.
In the beginning of the for loop you are picking out the k:th enemy from the army array. This could be either and Enemy or an Enemy2 object, but it cannot be both (unless there is some inheritage which we cannot see).
So what happens in your loop is that you pick out the last enemy, which is of type Enemy2, from the army array, and then you assign that enemy to your variable enemy, which is of type Enemy. This is where the conversion fails.
Probably you should have one Enemy class, and use this for both enemies, but if you want to use two different classes, you would have to do a type checking before operating on your enemy:
for (var k:int = army.length - 1; k >= 0; k--) {
if (army[k] is Enemy) {
enemy = army[k];
enemy.update();
if (enemy.y < 0) {
army.splice(k, 1);
enemy.parent.removeChild(enemy);
continue;
System.gc();
}
} else if (army[k] is Enemy2) {
enemy2 = army[k]
enemy2.update2();
if (enemy2.y < 0) {
army.splice(k, 1);
enemy.parent.removeChild(enemy);
continue;
System.gc();
}
}
}
The best, however, would be to make them inherit from the same base class, i.e.
class Enemy {
public var x;
public var y;
public function update() {...}
}
class Enemy1 extends Enemy {
override public function update() { // Enemy1 special updates }
}
class Enemy2 extends Enemy {
override public function update() { // Enemy2 special updates }
}

Related

hitTestObject doesn't work with veritable

trying to make bomb explode on impact when it hit the balls at the bottom of the stage, with if (bomb1.hitTestObject(ball)) { .But when the bomb hit one of the balls nothing happened. it works with other objects that are placed on stage but not with the balls.ball is a variable for 8 balls spread randomly on the bottom of the stage.
import flash.events.Event;
bomb1.gotoAndStop(1);
var minLimit: int = 31;
var maxLimit: int = 42;
var range: int = maxLimit - minLimit;
var balls: Array = [],
ball: bomb30a;
for (var i: int = 0; i < 8; i++) {
ball = new bomb30a();
ball.x = 150 + i * (Math.ceil(Math.random() * range) + minLimit);
ball.y = 350;
balls.push(ball);
addChild(ball);
}
thisButton.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event: MouseEvent): void {
bomb1.gotoAndPlay(1);
this.addEventListener(Event.ENTER_FRAME, handleCollision);
}
function handleCollision(evt: Event): void {
if (bomb1.hitTestObject(ball)) {
this.removeEventListener(Event.ENTER_FRAME, handleCollision);
bomb1.stop();
bomb1.bomb2.gotoAndPlay(31);
}
}
stop();
You are making eight bomb30a Objects, but you keep assigning them to the same variable, ball. This means that ball will, after your loop, refer to the last one only. So, when you do the hitTest, it is checking only the last ball you created. You will need to do a loop through your balls Array and try the hitTest on each on separately, as in...
for ( var i:int = 0; i < balls.length; ++i )
{
if ( bomb1.hitTestObject( balls[i] ) )
{
...
}
}

Level progression in a platform game? (Actionscript 3)

I've been working on a Platformer for a couple of weeks now and i can't seem to get the level progression working. I'm using a basic hitTest on a box to signal the movement from frame 1(level 1) to frame 2 (level 2) but once the character hits the exit box, i get the following error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at LevelProg_fla::MainTimeline/loop()
What can i do so that it moves to the next frame(level)? If it helps, my code is in a frame rather than a class. Basically, the only code that i'm using for level progression is
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
with "levelTwo" being the name of the next frame (next level). The rest of the game's code is as follows (pardon the messyness of it, I've been more focused on getting the darn thing to work :b)
import flash.events.KeyboardEvent;
import flash.events.Event;
//some variables to track the player's speed
var speedX = 0;
var speedY = 0;
player.height = 80.0;
player.width = 60.0;
//loop through all the platform objects to generate the level
var level:Array = new Array();
for (var i=0; i<numChildren; i++)
{
if (getChildAt(i) is platform)
{
level.push(getChildAt(i).getRect(this));
}
}
//make variables to store key states
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
//listen for key presses and releases
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=true;
if (k.keyCode==38) kUp=true;
if (k.keyCode==39) kRight=true;
if (k.keyCode==40) kDown=true;
}
function kU(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=false;
if (k.keyCode==38) kUp=false;
if (k.keyCode==39) kRight=false;
if (k.keyCode==40) kDown=false;
}
//Make a looping function
addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event)
{
//lateral movement checks
if (kLeft)
{
speedX=-10;
}
else if (kRight)
{
speedX=10;
}
else
{
speedX*=0.5; //friction to slow player down (kinda like mario)
}
//does not stop the character
//move player based on the above
player.x+=speedX;
//animations
if (speedX > 0)
{
trace("right pressed");
//player.gotoAndPlay("walkRight");
}
if (speedX < 0)
{
trace("left pressed");
//player.gotoAndPlay("walkLeft");
}
//sidewards hit tests
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedX > 0) ////moving right collision and stuffs
{
player.x = level[i].left-player.width/2;
}
if (speedX < 0) ////moving left collision and stuffs
{
player.x = level[i].right+player.width/2;
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//vertical checks
speedY+=1;
player.y+=speedY;
var jumpable = false
//vertical hitTests
//note that it's the same as the x code but just changed like 5 things.
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedY > 0) ////moving down collision and stuffs
{
player.y = level[i].top-player.height/2;
speedY=0;
jumpable = true;
}
if (speedY < 0) ////moving up collision and stuffs
{
player.y = level[i].bottom+player.height/2;
speedY*=-0.5; //bounces off cielings
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//jumps if possible
if (kUp && jumpable)
{
speedY=-15;
}
//gravity might help}
//move player with camera function/code/script/tired
this.x=-player.x+(stage.stageWidth/2); //centers the player
this.y=-player.y+(stage.stageWidth/2); //centers the player
//Progresses the player to level 2
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
}

How can I set the damage level of enemy

Thanks in advance...
I am having little bit doubt in my logic for setting the Damage level to the enemy in game. Following is my Enemy Class
package scripts.enemy
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Stage;
public class Enemy1 extends MovieClip
{
private var BG:MovieClip;
private var speed:Number = 0.5;
private var ease:Number = .005;
private var rad:Number = 57.2957795;
public function Enemy1(BG:MovieClip) : void
{
var RandomX:Array = new Array(-150,-200,-250,-300,-350,-400,-450,-500,-550,150,200,250,300,350,400,450,500,550);
var RandomY:Array = new Array(-150,-200,-250,-300,-350,-400,150,200,250,300,350,400);
var r:int = (Math.random() * 18);
var s:int = (Math.random() * 12);
x = RandomX[r];
y = RandomY[s];
this.BG = BG;
addEventListener(Event.ENTER_FRAME, moveEnemy); //false, 0, true);.
}
private function moveEnemy(e:Event):void
{
var dx:Number = x - 10;
var dy:Number = y - 10;
this.x -= dx * ease;
this.y -= dy * ease;
this.rotation = (Math.atan2(dy,dx) * rad) + 180;
}
}
}
And Here is some of code that giving me trouble from my Main class
// ......... Function for Checking the Collision between Bullet And Enemy...........
private function checkCollision(mc:MovieClip):Boolean
{
var test:Point = mc.localToGlobal( new Point());
for (var i = 0; i < enemies1.length; i++)
{
tempEnemy1 = enemies1[i];
if (kill == true)
{
if (tempEnemy1.hitTestPoint(test.x,test.y,true))
{
enemies1.splice(i, 1);
bg_mc.removeChild(tempEnemy1);
createDead(Dead1,deadArray1,tempEnemy1.x,tempEnemy1.y,tempEnemy1.rotation);
Score += 10;
Scr_txt.text = String(Score);
bugsKill += 1;
kill = false;
return true;
}
}
}
if (Level >= 2)
{
for (var j = 0; j < enemies2.length; j++)
{
tempEnemy2 = enemies2[j];
if (kill == true)
{
if (tempEnemy2.hitTestPoint(test.x,test.y,true))
{
bug2HitCount -= 1;
if (bug2HitCount == 0)
{
enemies2.splice(j, 1);
bg_mc.removeChild(tempEnemy2);
createDead(Dead2,deadArray2,tempEnemy2.x,tempEnemy2.y,tempEnemy2.rotation);
Score += 20;
Scr_txt.text = String(Score);
bugsKill += 1;
kill = false;
//bug2HitCount = bug2HitRate;
return true;
}
kill = false;
return true;
}
}
}
}
return false;
}
private function removeElement(removeList:Array):void
{
for (var i = 0; i < removeList.length; i++)
{
bg_mc.removeChild(removeList[i]);
}
}
//...........Function Checking the Collission Between Bunker And Enemy..............
private function collideEnemy(deadArray:Array,enemyArray:Array,rate:Number):void
{
var enemy:MovieClip;
for (var i = 0; i < enemyArray.length; i++)
{
enemy = enemyArray[i];
if (enemy.hitTestObject(bunker_mc))
{
life_mc.scaleX -= rate;
if (life_mc.scaleX <= 0.05)
{
stage.removeEventListener(Event.ENTER_FRAME,updateCollission);
Timer1.stop();
Mouse.show();
stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUpFun);
stage.removeEventListener(Event.ENTER_FRAME,updateStage);
stage.removeEventListener(MouseEvent.MOUSE_DOWN,mouseDownFun);
(player.parent).removeChild(player);
(bunker_mc.parent).removeChild(bunker_mc);
(life_mc.parent).removeChild(life_mc);
(sniper_mc.parent).removeChild(sniper_mc);
removeElement(bullets);
EndFun();
gunFire = false;
gotoAndStop("end");
Level = 1;
}
}
}
}
//...........function of Timer Complete Event.....................
private function TimerEnd(e:TimerEvent):void
{
EndBug();
gotoAndStop("end");
}
//...........function of Timer Complete Event.....................
private function EndBug():void
{
HelpTimer = new Timer(1000,1);
HelpTimer.addEventListener(TimerEvent.TIMER_COMPLETE,HelpFun);
HelpTimer.start();
stage.removeEventListener(Event.ENTER_FRAME,updateStage);
stage.removeEventListener(Event.ENTER_FRAME,updateCollission);
function HelpFun(Event:TimerEvent)
{
stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUpFun);
stage.removeEventListener(MouseEvent.MOUSE_DOWN,mouseDownFun);
gunFire = false;
bg_mc.removeChild(player);
bg_mc.removeChild(bunker_mc);
(life_mc.parent).removeChild(life_mc);
bg_mc.removeChild(sniper_mc);
EndFun();
Score = 0;
Level += 1;
totalBugs += 5;
}
}
//..................Function for ending the Game And removing the Reamining Enemies.................
private function EndFun():void
{
Mouse.show();
removeElement(dustArray);
if (Level == 1)
{
removeElement(enemies1);
removeElement(deadArray1);
gotoAndStop("level2");
}
if (Level == 2)
{
removeElement(enemies1);
removeElement(deadArray1);
removeElement(enemies2);
removeElement(deadArray2);
gotoAndStop("level3");
}
if (Level == 3)
{
......
}
.....................
.....................
}
}
}
In this code I have added a new type of Enemy in Level 2 and I have also written code for its HitTest property..In which each enemy of level 2 requires more than 1 bullet to kill.. But when I shoot a bullet to one enemy and then I shoot another bullet to another enemy of same type the another enemy gets killed. It means that the second enemy is getting killed in only 1 single bullet.. So how can I solve this issue..?
Please Help.. Thanks in advance..
The problem in your code lies within the checkCollision function. It basically goes over the first for loop and ignores the second. But it's best if you just assign the enemies health by adding a health parameter within your Enemy class and have each bullet decrease their health by 1. That way, you can just go through your array and remove any enemies that reach 0 health.
EDIT: I just looked over your code again and realized it's the bug2HitCount that's screwing everything up.

AS3 Flash: Spawning 2 same objects from 1 class?

I am creating a game in AS3, and in the class file for an enemy's bullet, I have this code.
public class enemy2Bullet extends MovieClip
{
public function enemy2Bullet()
{
stop();
//Setup an event listener to see if the bullet is added to the stage.
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
//Now that our object is on the stage, run our custom code.
init();
}
private function init():void
{
if (Math.random() <= 0.5)
{
addEventListener(Event.ENTER_FRAME, bullet2Loop)
}
else
{
addEventListener(Event.ENTER_FRAME, bullet2Loop2)
}
}
private function bullet2Loop(e:Event):void
{
if (currentLabel != "destroyed")
{
this.x += 8;
}
if (currentLabel == "destroyedComplete")
{
destroyEnemy2Bullet();
}
}
private function bullet2Loop2(e:Event):void
{
if (currentLabel != "destroyed")
{
this.x -= 8;
}
if (currentLabel == "destroyedComplete")
{
destroyEnemy2Bullet();
}
}
public function destroyEnemy2Bullet():void
{
{
//Remove the object from stage
stage.removeChild(this);
//Remove any event listeners
removeEventListener(Event.ENTER_FRAME, bullet2Loop);
}
}
}
After compiling, the game runs, but the bullet only shoots in 1 direction.
How can I make it such that the bullets are shot from both left and right, and stay in that direction?
Here's my enemy2 function.
private function enemy2Control():void
{
if (getTimer() - lastSpawnTime2 > 3000 && aEnemy2Array.length < 3)
{
var newEnemy2:MovieClip = new mcEnemy2;
newEnemy2.x = Math.random() * 800;
newEnemy2.y = 0;
aEnemy2Array.push(newEnemy2);
stage.addChild(newEnemy2);
lastSpawnTime2 = getTimer();
}
//Control enemy's bullets
for (var i:int = aEnemy2Array.length - 1; i >= 0; i--)
{
if (enemy2LastFire + 750 / (aEnemy2Array.length) < getTimer())
{
var currentEnemy2:mcEnemy2 = aEnemy2Array[i];
if (Math.random() < 0.06)
{
var newEnemy2Bullet:enemy2Bullet = new enemy2Bullet();
newEnemy2Bullet.x = currentEnemy2.x;
newEnemy2Bullet.y = currentEnemy2.y;
enemy2BulletArray.push(newEnemy2Bullet);
stage.addChild(newEnemy2Bullet);
enemy2LastFire = getTimer();
}
}
for (var j:int = enemy2BulletArray.length - 1; j >= 0; j--)
{
var currentEnemy2Bullet:enemy2Bullet = enemy2BulletArray[j];
if (currentEnemy2Bullet.y >= stage.stageHeight)
{
enemy2BulletArray.splice(j, 1);
currentEnemy2Bullet.destroyEnemy2Bullet();
}
if (currentEnemy2Bullet.hitTestObject(playerCore))
{
playerHP -= 1;
currentEnemy2Bullet.gotoAndPlay(2);
enemy2BulletArray.splice(j, 1);
}
}
}
}
Any help would be appreciated.
A few things:
• You can replace currentEnemy2Bullet with j and just delete the whole var currentEnemy2Bullet:enemy2Bullet = enemy2BulletArray[j]; statement.
• init() is never called. But it's best if you do the direction calculation and use newEnemy2Bullet.addEventListener(Event.ENTER_FRAME, whatever) within the actual initialization of newEnemy2Bullet.
• Truth to be told, your code is fairly messy and can be simplified. For example, you can just determine the direction of the bullet by giving the class a variable, give it a value on initialization, and have the loop update its position based on that variable.

ArgumentError: Error #2025

I get this error when I try my code:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Main_MouseFollow/onEnterFrame()[C:\Users\Ida\Documents\flash kursen\Space shooter del2\Main_MouseFollow.as:120]
line 120 is
removeChild(_bullets[j]);
Here is the entire code. I am new to Flash, so how can I fix this error?
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main_MouseFollow extends MovieClip
{
private var _bullets:Array;
private var _robotScore:Number;
private var _playerScore:Number;
public function Main_MouseFollow()
{
//Add event listeners
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.addEventListener("bulletCreated", onBulletCreated);
_bullets = new Array();
_robotScore = 0;
_playerScore = 0;
}
private function onAddedToStage(event:Event):void
{
addEventListener(Event.ENTER_FRAME, onEnterFrame);
addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
private function onRemovedFromStage(event:Event):void
{
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
private function onBulletCreated(event:Event)
{
_bullets.push(MovieClip(event.target));
}
private function onEnterFrame(event:Event):void
{
bulletDisplay.text = "Bullets on the stage: " + String(_bullets.length);
for (var i:int = 0; i < _bullets.length; i++)
{
switch (_bullets[i].bulletType)
{
case "circle" :
//Check for a collision with the player
if (player.hitTestPoint(_bullets[i].x,_bullets[i].y,true))
{
//Remove the bullet from the stage
removeChild(_bullets[i]);
//Remove bullet from array
_bullets.splice(i,1);
//Subtract 1 from the counter to compensate
//for the removed element
i--;
//Update the robot's score
_robotScore++;
//Update the robot's score display on the stage
robotScoreDisplay.text = String(_robotScore);
}
break;
case "star" :
//Check for a collision with the robot
if (robot.hitTestPoint(_bullets[i].x,_bullets[i].y,true))
{
//Remove the bullet from the stage
removeChild(_bullets[i]);
//Remove bullet from array
_bullets.splice(i, 1);
//Subtract 1 from the counter to compensate
//for the removed element
i--;
//Update the enemy's score
_playerScore++;
//Update the player's score display on the stage
playerScoreDisplay.text = String(_playerScore);
}
break;
}
}
//Bullet stage Boundaries:
for (var j:int = 0; j < _bullets.length; j++)
{
//Top
if (_bullets[j].y + _bullets[j].height / 2 < 0)
{
removeChild(_bullets[j]);
_bullets.splice(j, 1);
j--;
}
//Bottom
else if (_bullets[j].y - _bullets[j].height / 2 > stage.stageHeight)
{
removeChild(_bullets[j]);
_bullets.splice(j, 1);
j--;
}
//Left
else if (_bullets[j].x + _bullets[j].width / 2 < 0)
{
removeChild(_bullets[j]);
_bullets.splice(j, 1);
j--;
}
//Right
else if (_bullets[j].x - _bullets[j].width / 2 > stage.stageWidth)
{
removeChild(_bullets[j]);
_bullets.splice(j, 1);
j--;
}
}
}
}
}
try to remove child in more safety way:
replace (in all 4 cases):
removeChild(_bullets[j]);
with:
if(_bullets[j].parent)
_bullets[j].parent.removeChild(_bullets[j]);
this will removes the error. If there aren't any other problems in logic this will fix the whole issue.