ArgumentError: Error #2025 - actionscript-3

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.

Related

add two enemy in one array AS3

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 }
}

Error #1034: Type Coercion failed: cannot convert flash.display::Stage#27dfe089 to flash.display.MovieClip

here it is the error >> TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::Stage#261b4089 to flash.display.MovieClip.
at com.ply::Heli/fireBullet()
at com.ply::Heli/myOnPress()
this is Heli's Class :
package com.ply
{
import flash.display.MovieClip;
import flash.display.*;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import com.peluru.Bullet;
public class Heli extends MovieClip
{
var shotCooldown:int;
const MAX_COOLDOWN = 10;
//Settings
public var xAcceleration:Number = 0;
public var yAcceleration:Number = 0;
private var xSpeed:Number = 0;
private var ySpeed:Number = 0;
private var up:Boolean = false;
private var down:Boolean = false;
private var left:Boolean = false;
private var right:Boolean = false;
public function Heli()
{
shotCooldown = MAX_COOLDOWN;
bullets = new Array();
addEventListener(Event.ENTER_FRAME, update);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
init();
}
private function init():void
{
addEventListener(Event.ENTER_FRAME, RunHeli);
}
private function RunHeli(event:Event):void
{
xSpeed += xAcceleration ; //increase the speed by the acceleration
ySpeed += yAcceleration ; //increase the speed by the acceleration
xSpeed *= 0.95; //apply friction
ySpeed *= 0.95; //so the speed lowers after time
if(Math.abs(xSpeed) < 0.02) //if the speed is really low
{
xSpeed = 0; //set it to 0
//Otherwise I'd go very small but never really 0
}
if(Math.abs(ySpeed) < 0.02) //same for the y speed
{
ySpeed = 0;
}
xSpeed = Math.max(Math.min(xSpeed, 10), -10); //dont let the speed get bigger as 10
ySpeed = Math.max(Math.min(ySpeed, 10), -10); //and dont let it get lower than -10
this.x += xSpeed; //increase the position by the speed
this.y += ySpeed; //idem
}
public function update(e:Event){
shotCooldown-- ;
}
/**
* Keyboard Handlers
*/
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
yAcceleration = 1;
}
else if (event.keyCode == 32)
{
fireBullet();
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
yAcceleration = 0;
}
}
public function fireBullet() {
if (shotCooldown <=0 )
{
shotCooldown=MAX_COOLDOWN;
var b = new Bullet();
var b2= new Bullet();
b.x = this.x +20;
b.y = this.y ;
b2.x= this.x -20;
b2.y= this.y ;
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
trace(bullets.length);
parent.addChild(b);
parent.addChild(b2);
}
}
}
}
and this is the Main Class
package
{
import com.ply.Heli;
import com.peluru.Bullet;
import com.musuh.Airplane2;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.*;
import flash.events.*;
import flash.utils.*;
public class Main extends MovieClip
{
public static const STATE_INIT:int = 10;
public static const STATE_START_PLAYER:int = 20;
public static const STATE_PLAY_GAME:int = 30;
public static const STATE_REMOVE_PLAYER:int = 40;
public static const STATE_END_GAME:int = 50;
public var gameState:int = 0;
public var player:Heli;
public var enemy:Airplane2;
//public var bulletholder:MovieClip = new MovieClip();
//================================================
public var cTime:int = 1;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 10;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 64;
//the player's score
public var score:int = 0;
public var gameOver:Boolean = false;
public var bulletContainer:MovieClip = new MovieClip();
//================================================
private var nextPlane:Timer;
public var enemies:Array;
public var bullets:Array;
public function Main()
{
gameState = STATE_INIT;
gameLoop();
}
public function gameLoop(): void {
switch(gameState) {
case STATE_INIT :
initGame();
break
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY_GAME:
playGame();
break;
case STATE_REMOVE_PLAYER:
//removePlayer();
break;
case STATE_END_GAME:
break;
}
}
public function initGame() :void {
enemies = new Array();
bullets = ne Array();
setNextPlane();
gameState = STATE_START_PLAYER;
gameLoop();
//stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
stage.addEventListener(Event.ENTER_FRAME, back);
stage.addEventListener(Event.ENTER_FRAME,checkForHits);
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
// create plane
var enemy:Airplane2 = new Airplane2();
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
enemies.push(enemy);
// set time for next plane
setNextPlane();
}
public function removePlane(plane:Airplane2) {
for(var i in enemies) {
if (enemies[i] == plane) {
enemies.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullet) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=enemies.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(enemies[airplaneNum])) {
enemies[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
trace("kena");
//shotsHit++;
//showGameScore();
break;
}
}
}
//if ((shotsLeft == 0) && (bullets.length == 0)) {
// endGame();
//}
}
public function back( evt:Event ):void
{ // Backgroud Land
if (Dessert2.y >= 0 && Dessert.y >= 720)
{
Dessert.y = Dessert2.y - 1240 ;
}
else if (Dessert.y >= 0 && Dessert2.y >= 720)
{
Dessert2.y = Dessert.y - 1240 ;
}
else
{
Dessert.y = Dessert.y +5 ;
Dessert2.y = Dessert2.y +5 ;
}
// Background Clouds
if (Clouds2.y >= 0 && Clouds.y >= 720)
{
Clouds.y = Clouds2.y - 2480 ;
}
else if (Clouds.y >= 0 && Clouds2.y >= 720)
{
Clouds2.y = Clouds.y - 2480 ;
}
else
{
Clouds.y = Clouds.y +10 ;
Clouds2.y = Clouds2.y +10 ;
}
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
gameLoop();
//txtScore.text = 'Score: '+score;
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
enemyTime ++;
} else {
//defining a variable which will hold the new enemy
enemy =new Airplane2();
//making the enemy offstage when it is created
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
//and reset the enemyTime
enemyTime = 0;
}
if(cTime <= cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 1;
}
}
}
}
You have added your player in Main into stage instead of this - why, by the way? So, there are two methods of fixing this: First, change line where you add player to display list, and second, remove direct coercion from Heli.fireBullet() function. I'd say use the first one.
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
this.addChild(player); // <-- this, not stage
gameState = STATE_PLAY_GAME;
}
Change
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
to
MovieClip(root).bullets.push(b);
MovieClip(root).bullets.push(b2);

AS3 Generating differnet Enemies and bullets hitTest Problems

I'm creating a 2d side scrolling shooter with 4 different types of Enemies and 3 different types of bullets. I'm using a factory class to create the enemies and a for loop inside a for loop to do hit testing. When I run my code for some reason when one enemy get's hit some of my other enemies die. Could someone please help me locate and fix my problem.
Here's one of the Enemy classes. The other 3 are identical except with different var values.
package char {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Enemy1 extends MovieClip {
private var _type:String;
private var _health:Number;
private var _vx:Number;
private var _vy:Number;
private var _stage:Stage;
private static var _instance:Enemy1;
public function Enemy1() {
init();
}
private function init():void {
//Vars
_vx = -5;
_vy = Math.random()*5;
_health = 1;
_stage = Main.getStage();
_instance = this;
//Listeners
addEventListener(Event.ADDED_TO_STAGE, onAdded);
addEventListener(Event.ENTER_FRAME, enemyLoop);
addEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
}
//When Added
private function onAdded(event:Event):void{
//Set position
this.x = _stage.stageWidth;
this.y = Math.random() * _stage.stageHeight;
//trace("Enemy created");
dispatchEvent(new Event("enemyCreated", true));
}
//Loop
private function enemyLoop(event:Event):void {
//Move
x += _vx;
y += _vy;
//Boundaries
if ( this.y <= 0 + this.height/2){
this.y = this.height/2;
_vy *= -1;
}
if ( this.y >= _stage.stageHeight - this.width/2){
this.y = _stage.stageHeight - this.width/2;
_vy *= -1;
}
//Health cheack
if ( _health <= 0){
if (this.parent) {
this.parent.removeChild(this);
Main.setScore(10);
}
}
//Leaves screen
if (this.x <= -this.width){
if (this.parent) {
this.parent.removeChild(this);
}
}
}
public function isHit(type:String):void{
//trace(this + " is hit by " + type);
if(type == "power"){
_health -= 1;
trace(_health);
}
else if(type == "quick"){
_health -= 1;
trace(_health);
}
else if(type == "strong"){
_health -= 1;
trace(_health);
}
}
public function getHealth():Number{
return _health;
}
public function getEnemy1():Enemy1{
return _instance;
}
//When Removed
private function onRemoved(event:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, onAdded);
removeEventListener(Event.ENTER_FRAME, enemyLoop);
removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
//trace("enemy removed");
}
}
}
And here's my main class that checks for all the hitTests
package screen {
import flash.display.MovieClip;
import flash.events.Event;
import com.greensock.TweenLite;
import com.greensock.easing.*;
import char.Player;
import char.EnemyFactory;
public class Level1 extends MovieClip {
//Consts
private const ENEMY_CHANCE:Number = 0.025;
//Vars
private var _player:Player;
private var _enemyBudget:Number = 20;
private static var _bullets:Array = [];
private static var _enemies:Array = [];
public function Level1() {
init();
}
private function init():void {
//Vars
this.alpha = 0;
_enemyBudget = 20;
//Event listeners
addEventListener(Event.ENTER_FRAME, levelLoop);
addEventListener(Event.ADDED_TO_STAGE, onAdded);
addEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
//Add This
Main.getInstance().addChild(this);
}
private function onAdded(event:Event):void {
TweenLite.to(this, 0.5, {alpha:1});
_player = new Player();
trace("Level 1 reaady");
}
private function levelLoop(event:Event):void{
//Health bar
_healthBar.scaleX = Main.getPlayerHealth() / 100;
//enemy creation
if(_enemyBudget <= 20 && _enemyBudget > 10){
if (ENEMY_CHANCE > Math.random()){
var randomEnemy:Number = Math.random()* 1.2;
//trace(randomEnemy);
if(randomEnemy <= 0.5){
//trace("Enemy 1");
var enemy1:MovieClip = char.EnemyFactory.makeEnemy("weak");
Main.getInstance().addChild(enemy1);
_enemyBudget -= 1;
}
else if(randomEnemy > 0.5 && randomEnemy <= 0.8){
//trace("Enemy 2");
var enemy2:MovieClip = char.EnemyFactory.makeEnemy("quick");
Main.getInstance().addChild(enemy2);
_enemyBudget -= 3;
}
else if(randomEnemy > 0.8 && randomEnemy <= 1){
//trace("Enemy 3");
var enemy3:MovieClip = char.EnemyFactory.makeEnemy("strong");
Main.getInstance().addChild(enemy3);
_enemyBudget -= 3;
}
else if(randomEnemy > 1 && randomEnemy <= 1.2){
//trace("Enemy 4");
var enemy4:MovieClip = char.EnemyFactory.makeEnemy("power");
Main.getInstance().addChild(enemy4);
_enemyBudget -= 4;
}
}
}
else if(_enemyBudget <= 10 && _enemyBudget > 0){
if (ENEMY_CHANCE > Math.random()){
var randomEnemy:Number = Math.random();
if(randomEnemy <= 0.5){
//trace("Enemy 1");
var enemy1:MovieClip = char.EnemyFactory.makeEnemy("weak");
Main.getInstance().addChild(enemy1);
_enemyBudget -= 1;
}
else if(randomEnemy > 0.5 && randomEnemy <= 0.8){
//trace("Enemy 2");
var enemy2:MovieClip = char.EnemyFactory.makeEnemy("quick");
Main.getInstance().addChild(enemy2);
_enemyBudget -= 3;
}
else if(randomEnemy > 0.8 && randomEnemy <= 1){
//trace("Enemy 3");
var enemy3:MovieClip = char.EnemyFactory.makeEnemy("strong");
Main.getInstance().addChild(enemy3);
_enemyBudget -= 3;
}
}
}
else if(_enemyBudget <= 0){
if(_enemies == []){
trace("Game End");
}
}
if( Main.getPlayerHealth() <= 0){
trace("Player Dead. End Game");
}
for (var i:int = 0; i < _enemies.length; i++){
for(var j:int = 0; j < _bullets.length; j++){
if(_bullets[j] != null && _enemies[i] != null){
//Check if bullet hits enemy
if(_bullets[j].hitTestObject(_enemies[i])){
//removes bullet
if (_bullets[j].parent) {
_bullets[j].parent.removeChild(_bullets[j]);
}
//Tells enemy he's hit
if(_enemies[i] != null){
_enemies[i].isHit(_bullets[j].getType());
}
//Checks enemy health
if(_enemies[i].getHealth() <= 0){
if(_enemies[i] == null){
_enemies.splice(i, 1);
i--;
}
}
//Removes bullet from array
if(_bullets[j] == null){
_bullets.splice(j, 1);
j--;
}
}
//Check if player hit
if(_enemies[i] != null && _player != null){
if(_enemies[i].hitTestObject(_player)){
if (_enemies[i].parent) {
_enemies[i].parent.removeChild(_enemies[i]);
Main.setPlayerHealth(-10);
}
}
if(_enemies[i] == null){
_enemies.splice(i, 1);
i--;
}
}
}
}
}
}
private function onRemoved(event:Event):void{
removeEventListener(Event.ENTER_FRAME, levelLoop);
removeEventListener(Event.ADDED_TO_STAGE, onAdded);
removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
}
//Get instance
public static function addBullet(bullet:MovieClip):void {
_bullets.push(MovieClip(bullet));
}
public static function addEnemy(enemy:MovieClip):void{
_enemies.push(MovieClip(enemy));
//trace(enemy + " was added to enemy array.");
}
}
}
And here's the function inside the Bullet class that return's it's type.
public function getType():String{
return TYPE;
}
It's hard to say with certainty, this would be easy to confirm by stepping through the code in a debugger.
But what looks suspicious to me is that you're iterating over arrays of enemies/bullets, and in the middle of doing that, you delete elements from the array and decrement the counter variables. Generally, when you need to iterate over something and potentially remove elements from the thing you're iterating over, you should do that iteration in a backwards fashion. That way changing the length and contents of the array in the middle of the loop is harmless.
for (var i:int = enemeies.length -1; i >= 0; i--)
{
// do your stuff and remove elements from the
// enemies array at will ... just splice the current
// element at index i out here, don't decrement i as
// you've done in your code above it will get decremented
// by the for loop
}

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.