Remove timer event listener - actionscript-3

so I need to remove a timer event. But the problem is, It's in another function so I can't access it.
Here's how my code goes:
-There is a Boss
-It generates bomb
-Bomb lasts for a couple of seconds before exploding (no error)
-Bomb can be removed by clicking. (generates error)
If the bomb was removed via clicking, there will be error because the time event wasn't remove. But like I said, I can't remove it because it's in another function. Help!
import flash.events.Event;
import flash.display.MovieClip;
var boss:MovieClip = new darklord();
this.addChild(boss);
boss.x = stage.stageWidth / 2;
boss.y = stage.stageHeight / 2;
var lives:int = 3;
var maxHP:int = 2000;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;
var bombcontainer:Array = [];
var timecontainer:Array = [];
function updateHealthBar():void
{
percentHP = currentHP / maxHP;
healthBar.barColor.scaleX = percentHP;
}
boss.addEventListener(MouseEvent.CLICK, TapBoss);
boss.addEventListener(Event.ENTER_FRAME, MoveBoss);
function TapBoss(e:MouseEvent):void
{
currentHP -= 10;
if (currentHP <= 0)
{
currentHP = 0;
trace("You win!");
}
updateHealthBar();
}
var timerBoss:Timer = new Timer(1000,60);
timerBoss.addEventListener(TimerEvent.TIMER, bosstimerhandler);
timerBoss.start();
var secondsBoss:Number = 0;
function bosstimerhandler(event:TimerEvent)
{
//trace("Seconds elapsed: " + seconds);
//SpawnNote(null);
if (secondsBoss%5==0)
{
RandomCoord(null);
BossAttack(null);
}
secondsBoss++;
}
var HighH:int = stage.stageHeight;
var HighW:int = stage.stageWidth;
var LowH:int = 0;
var LowW:int = 0;
var destinationX:int;
var destinationY:int;
function RandomCoord(event:Event):void
{
destinationX=Math.floor(Math.random()*(1+HighW-LowW))+LowW;
destinationY=Math.floor(Math.random()*(1+HighH-LowH))+LowH;
if (destinationX <= 50)
{
destinationX += 50;
}
if (destinationY <= 50)
{
destinationY += 50;
}
if (destinationX + 50 >= stage.stageWidth)
{
destinationX -= 50;
}
if (destinationY + 50 >= stage.stageHeight)
{
destinationY -= 50;
}
trace("X is: ", destinationX);
trace("Y is: ", destinationY);
}
function MoveBoss(event:Event):void
{
if (boss.x < destinationX)
{
boss.x += 1;
}
else if (boss.x > destinationX)
{
boss.x -= 1;
}
if (boss.y < destinationY)
{
boss.y += 1;
}
else if (boss.y > destinationY)
{
boss.y -= 1;
}
}
function BossAttack(event:Event):void
{
var boom:MovieClip = new Bomb();
this.addChild(boom);
bombcontainer.push(boom);
boom.x = boss.x;
boom.y = boss.y;
BombCoord(null);
boom.addEventListener(Event.ENTER_FRAME, MoveBomb);
boom.addEventListener(MouseEvent.CLICK, TapBomb(boom));
BombTimer(boom);
}
function BombTimer(boom:MovieClip):void
{
var time:Timer = new Timer(1000,30);
timecontainer.push(time);
time.addEventListener(TimerEvent.TIMER, TimeHandler);
time.start();
var t:Number = 1;
function TimeHandler(event:TimerEvent):void
{
trace("Seconds elapsed: " + t);
t++;
if (t==12)
{
lives--;
trace("You lost a life!");
time.removeEventListener(TimerEvent.TIMER, TimeHandler);
RemoveBomb(boom, 0);
}
}
}
function RemoveBomb(boom:DisplayObject, bid:int):void
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
//boom.removeEventListener(MouseEvent.CLICK, TapBomb(boom));
bombcontainer.splice(bid, 1);
trace("Bomb # :" +bid+" is popped.");
this.removeChild(boom);
}
var BombX:int;
var BombY:int;
function BombCoord(event:Event):void
{
BombX=Math.floor(Math.random()*(1+HighW-LowW))+LowW;
BombY=Math.floor(Math.random()*(1+HighH-LowH))+LowH;
if (BombX <= 50)
{
BombX += 50;
}
if (BombY <= 50)
{
BombY += 50;
}
if (BombX + 50 >= stage.stageWidth)
{
BombX -= 50;
}
if (BombY + 50 >= stage.stageHeight)
{
BombY -= 50;
}
}
function MoveBomb(event:Event):void
{
var boom:DisplayObject = event.target as DisplayObject;
var fl_TimerInstance:Timer = new Timer(1000,6);
fl_TimerInstance.addEventListener(TimerEvent.TIMER, fl_TimerHandler);
fl_TimerInstance.start();
var fl_SecondsElapsed:Number = 1;
function fl_TimerHandler(event:TimerEvent):void
{
//trace("Seconds elapsed: " + fl_SecondsElapsed);
fl_SecondsElapsed++;
if (fl_SecondsElapsed==4)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
if (boom.x < BombX)
{
boom.x += 5;
//boom.x +=5;
}
else if (boom.x > BombX)
{
boom.x -= 5;
}//boom.x -=5;
if (boom.y < BombY)
{
boom.y += 5;
//boom.x +=5;
}
else if (boom.y > BombY)
{
boom.y -= 5;
}
if (boom.x == BombX)
{
if (boom.y == BombY)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
if (boom.y == BombY)
{
if (boom.x == BombX)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
}
function TapBomb(boom:MovieClip):Function
{
return function(e:MouseEvent):void {
var BombIndex:int = bombcontainer.indexOf(boom);
trace("You clicked the bomb at index " + BombIndex);
RemoveBomb(boom, BombIndex);
}
}

It's not that bad having a frame event listener on each bomb, unless perhaps you have hundreds of bombs at the same time.
You can solve the issue by making the Bomb a separate class that has its own handlers and timer. Something like this (not tested):
package {
import flash.display.*;
import flash.net.*;
import flash.utils.Timer;
public class Bomb extends MovieClip {
private var myTimer:Timer;
public function Bomb() {
myTimer = new Timer(1000,30);
myTimer.addEventListener(TimerEvent.TIMER, TimeHandler);
myTimer.start();
}
private function TimeHandler(event:TimerEvent):void {
// check the time
}
public function stopTicking():void {
this.myTimer.stop();
}
}
}
You can then create all the bombs you want and kill their timers by calling their method:
// create a bomb movieclip and add it to the displaylist
var myBomb = new Bomb();
bombContainer.addChild(myBomb);
// use the displaylist to keep track of nonexploded bombs
var someBomb = bombContainer.getChildAt(0);
// stop the timer on this bomb
someBomb.stopTicking();

Related

Actionscript 3 - ReferenceError: Error #1065: Variable addFrameScript is not defined

I am getting this error :
ReferenceError: Error #1065: Variable addFrameScript is not defined.
at survival()
I'm having the problem when I run this code :
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.*;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
public class survival extends Sprite {
public var ground:ground_mc = new ground_mc();
public var environment:environment_mc = new environment_mc();
public var player:player_mc = new player_mc();
public var monster:monster_mc = new monster_mc();
public var light:Sprite=new Sprite ;
public var battery:battery_mc = new battery_mc();
public var key_pressed:int=0;
public var radius:int=8;
public var player_speed:int=2;
public var monster_speed:int=1;
public var torch_power:int=150;
public var torch_step:int = 100;
public var torch_angle:int=60;
public var torch_angle_step:int=35;
public var up,down,left,right:Boolean=false;
public var flicker=0;
public var count:int;
public var sec:int;
public var torchBattery:int = 100;
var topLeft:Boolean = true;
var topRight:Boolean = false;
var bottomLeft:Boolean = false;
var bottomRight:Boolean = false;
public function survival():void {
addChild(ground);
addChild(environment);
addChild(light);
addChild(player);
addChild (battery);
addChild(monster);
player.x=250;
player.y=200;
battery.x=321;
battery.y=29;
environment.y = 0;
environment.x = 0;
ground.mask=light;
addEventListener(Event.ENTER_FRAME,on_enter_frame);
addEventListener(Event.ENTER_FRAME,on_enter_frame2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, on_key_down);
stage.addEventListener(KeyboardEvent.KEY_UP, on_key_up);
}
public function on_enter_frame(e:Event):void {
if (up) {
environment.y+=player_speed;
ground.y+=player_speed;
monster.y+=player_speed;
}
if (down) {
environment.y-=player_speed;
ground.y-=player_speed;
monster.y-=player_speed;
}
if (left) {
environment.x+=player_speed;
ground.x+=player_speed;
monster.x+=player_speed;
}
if (right) {
environment.x-=player_speed;
ground.x-=player_speed;
monster.x-=player_speed;
}
if (environment.collisions.hitTestPoint(player.x, player.y+radius, true)) {
environment.y+=player_speed;
ground.y+=player_speed;
monster.y+=player_speed;
}
if (environment.collisions.hitTestPoint(player.x, player.y-radius, true)) {
environment.y-= player_speed;
ground.y-= player_speed;
monster.y-= player_speed;
}
if (environment.collisions.hitTestPoint(player.x-radius, player.y, true)) {
environment.x-= player_speed;
ground.x-= player_speed;
monster.x-= player_speed;
}
if (environment.collisions.hitTestPoint(player.x+radius, player.y, true)) {
environment.x+= player_speed;
ground.x+= player_speed;
monster.x+= player_speed;
}
var dist_x:Number=player.x-mouseX;
var dist_y:Number=player.y-mouseY;
var angle:Number=- Math.atan2(dist_x,dist_y);
player.rotation=to_degrees(angle);
light.graphics.clear();
if (Math.random()*100>flicker) {
light.graphics.beginFill(0xffffff, 100);
light.graphics.moveTo(player.x, player.y);
for (var i:int=0; i<=torch_angle; i+=(torch_angle/torch_angle_step)) {
ray_angle = to_radians((to_degrees(angle)-90-(torch_angle/2)+i));
for (var j:int=1; j<=torch_step; j++) {
if (environment.collisions.hitTestPoint(player.x+(torch_power/torch_step*j)*Math.cos(ray_angle), player.y+(torch_power/torch_step*j)*Math.sin(ray_angle), true)) {
break;
}
}
light.graphics.lineTo(player.x+(torch_power/torch_step*j)*Math.cos(ray_angle), player.y+(torch_power/torch_step*j)*Math.sin(ray_angle));
}
light.graphics.lineTo(player.x, player.y);
light.graphics.endFill();
}
if (torchBattery > 0) {
count += 1;
if (count >= 30) {
count = 0;
sec += 1;
}
if (sec >= 2) {
sec = 0;
flicker += 1;
torchBattery -= 1;
changeMovement();
}
}
battery.battery.text = "Torch Battery: " + torchBattery + "%";
var theDistance:Number = distance(monster.x, player.x, monster.y, player.y);
var myVolume:Number = 2-(0.004* theDistance);
var Volume:Number = myVolume;
if (Volume < 0) {
Volume = 0;
}
SoundMixer.soundTransform = new SoundTransform(Volume);
trace(theDistance);
if (distance < 100) {
removeEventListener(Event.ENTER_FRAME,on_enter_frame);
removeEventListener(Event.ENTER_FRAME,on_enter_frame2);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, on_key_down);
stage.removeEventListener(KeyboardEvent.KEY_UP, on_key_up);
removeChild(ground);
removeChild(environment);
removeChild(light);
removeChild(player);
removeChild (battery);
removeChild(monster);
gotoAndStop(2);
}
}
function on_enter_frame2 (e:Event) :void {
if (environment.collisions.hitTestPoint(monster.x, monster.y+radius, true)) {
monster.y -= monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x,monster.y-radius, true)) {
monster.y += monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x-radius, monster.y, true)) {
monster.x+=monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x+radius, monster.y, true)) {
monster.x -= monster_speed;
}
if (topLeft) {
monster.x -= monster_speed;
monster.y -= monster_speed;
} else if (topRight) {
monster.x += monster_speed;
monster.y -= monster_speed;
} else if (bottomLeft) {
monster.x -= monster_speed;
monster.y += monster_speed;
} else if (bottomRight) {
monster.x += monster_speed;
monster.y += monster_speed;
}
}
function changeMovement():void {
var die2:Number = Math.floor(Math.random()*4);
if (die2 == 1) {
topLeft = true;
topRight = false;
bottomLeft = false;
bottomRight = false;
}
if (die2 == 2) {
topLeft = false;
topRight = true;
bottomLeft = false;
bottomRight = false;
}
if (die2 == 3) {
topLeft = false;
topRight = false;
bottomLeft = true;
bottomRight = false;
}
if (die2 == 4) {
topLeft = false;
topRight = false;
bottomLeft = false;
bottomRight = true;
}
}
public function on_key_down(e:KeyboardEvent):void {
switch (e.keyCode) {
case 37 :
left=true;
break;
case 38 :
up=true;
break;
case 39 :
right=true;
break;
case 40 :
down=true;
break;
/*case 49 :
torch_power++;
break;
case 50 :
torch_power--;
break;*/
}
}
public function on_key_up(e:KeyboardEvent):void {
switch (e.keyCode) {
case 37 :
left=false;
break;
case 38 :
up=false;
break;
case 39 :
right=false;
break;
case 40 :
down=false;
break;
}
}
public function to_radians(n:Number):Number {
return (n*0.0174532925);
}
public function to_degrees(n:Number):Number {
return (n*57.2957795);
}
function distance(x1:Number, x2:Number, y1:Number, y2:Number): Number {
var dx:Number = x1-x2;
var dy:Number = y1-y2;
return Math.sqrt(dx * dx + dy * dy);
}
}
}
On my timeline I have a blank keyframe with the sound effect of a music box playing, and a second frame with the animated jumpscare. The game is that you're in a bird's eye view of a person with a torch walking through a maze. The 'monster' moves around the maze and you must stay away from it. As it gets closer, the music box that is playing will get louder. Also, your torch only has a certain amount of battery. As the battery reduces, the torch will flicker more untill it eventually stops working. It worcked fine until I tried to make the jumpscare. This is all the coding in the game.
In the 'Compiler Errors' it also states:
/Users/ethan/Documents/Flash Stuff/Flash Stuff [from macbook]/survival/survival.as, Line 164 Warning: 1060: Migration issue: The method gotoAndStop is no longer supported. For more information, see MovieClip.gotoAndStop()..
Any suggestions or help I'll be very grateful.
Sprite Class doesn't have gotoAndStop method. This method implemented only in MovieClip class. So, you should replace
public class survival extends Sprite {
with
public class survival extends MovieClip {

How to implement enemy behaviour based on type?

I am building a game which create three types of enemy.Amount them only type 3 can fire others cannt.This is my enemy class
package
{
import flash.display.MovieClip;
import flash.utils.getTimer;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.Point;
public class Enemy extends MovieClip
{
private var lastTime:int;
var hitCounter:Number = 1;
public var eType:Number = 0;
private var startYpos:Number = 0;
var nextFire:Timer;
var enemyType:Number;
public var bullets:Array = new Array ;
var speedY:Number = 50;
var enemySpeed:Number = 50;
var firstPos:Number = 0;
var fireCounter:Number = 0;
var firePause:Number = 10;
public function Enemy(xPos,yPos:Number,t:Number)
{
// constructor code
this.x = xPos;
firstPos = this.y = yPos;
this.enemyType = t;
lastTime = getTimer();
this.gotoAndStop(t);
addEventListener(Event.ENTER_FRAME,moveEnemy);
}
public function moveEnemy(event:Event)
{
// get time passed
var timePassed:int = getTimer() - lastTime;
lastTime += timePassed;
// move bullet
if (this.y + this.height / 2 > firstPos + 100 && speedY > 0)
{
speedY *= -1;
}
if (this.y - this.height / 2 < firstPos && speedY < 0)
{
speedY *= -1;
}
this.x -= enemySpeed * timePassed / 1000;
this.y += speedY * timePassed / 1000;
// bullet past top of screen
if (this.x - this.width / 2 < 0)
{
deleteEnemy();
}
if (this.enemyType == 3)
{
canFire();
}
}
public function canFire()
{
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
public function deleteEnemy()
{
if (this.currentFrame == 2)
{
this.gotoAndStop(4);
}
else
{
//trace(MovieClip(parent).enemyKilled[this.enemyType-1]);
MovieClip(parent).enemyKilled[this.enemyType - 1]++;
MovieClip(parent).removeEnemy(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveEnemy);
}
}
}
}
Now once a enemy type 3 start firing then every enemy start firing.i want just only enemy type 3 can fire not other enemy.How i do it?
Thanks in advance
Addition :
public function createEnemyBullet()
{
var bullet:Bullet = new Bullet(enemy.x - 10,enemy.y,500,-1);
bullets.push(bullet);
addChild(bullet);
//setEnemyBullet();
}
Then why don't you try something like this. `
public function canFire()
{
if(enemyType == 3){
return;
}
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
`

Error 1136 : incorrect number of arguments. Expected 0

can anybody tell me what is wrong with this code ...How to solve this code i use this code make monster move to the checkpoints...but all of the check points get some warning from Line 22-30 1136: Incorrect number of arguments. Expected 0.
package Game
{
import flash.display.MovieClip;
import flash.events.*;
import flash.geom.*;
public class Monster extends MovieClip
{
public var currLife:Number;
private var maxLife, gold, speed, currIndex, slowTimer:Number;
private var checkPoints:Array;
public function Monster()
{
maxLife = C.MONSTER_LIFE;
currLife = maxLife;
speed = C.MONSTER_SPEED;
currIndex = 0;
checkPoints = new Array();
checkPoints.push(new Point(85,140));
checkPoints.push(new Point(85,320));
checkPoints.push(new Point(325,320));
checkPoints.push(new Point(325,200));
checkPoints.push(new Point(265,200));
checkPoints.push(new Point(265,80));
checkPoints.push(new Point(505,80));
checkPoints.push(new Point(505,380));
checkPoints.push(new Point(630,380));
}
public function update()
{
var finalSpeed:Number;
if (slowTimer > 0)
{
finalSpeed = speed / 2;
slowTimer--;
}
else
finalSpeed = speed;
if (currIndex < checkPoints.length)
{
//move in the direction of the checkpoint
if (this.x < checkPoints[currIndex].x)
this.x += Math.min(finalSpeed, Math.abs(this.x -
checkPoints[currIndex].x));
else if (this.x > checkPoints[currIndex].x)
this.x -= Math.min(finalSpeed, Math.abs(this.x -
checkPoints[currIndex].x));
if (this.y < checkPoints[currIndex].y)
this.y += Math.min(finalSpeed, Math.abs(this.y -
checkPoints[currIndex].y));
else if (this.y > checkPoints[currIndex].y)
this.y -= Math.min(finalSpeed, Math.abs(this.y -
checkPoints[currIndex].y));
if ((this.x == checkPoints[currIndex].x) &&
(this.y == checkPoints[currIndex].y))
{
currIndex += 1;
}
}
//display
if (currLife > 0)
mcLifeBar.width = Math.floor((currLife/maxLife)*
C.LIFEBAR_MAX_WIDTH);
else
mcLifeBar.width = 0;
}
public function takeDamage(amtDamage)
{
if (this.currLife <= 0)
return;
this.currLife -= amtDamage;
if (this.currLife <= 0)
{
this.gotoAndPlay("death");
}
}
public function slowDown(amt)
{
slowTimer = amt;
}
public function hasReachedDestination()
{
return (this.currIndex == checkPoints.length);
}
}
}
Please help me to solve this problem ...i'm just a noob in AS3
i use that code in above for GameController.as
and this is update for GameController
public function update(evt:Event)
{
//Update the mobs
if ((currWave < maxWave) && (monsters.length == 0))
{
currWave++;
//spawn the monsters
spawnWave(currWave);
}
for (i=monsters.length - 1; i >= 0; i--)
{
if (monsters[i].currLife > 0)
{
monsters[i].update();
}
//Check if monster reaches the end of their path
if (monsters[i].hasReachedDestination())
{
monsters[i].gotoAndStop("remove");
life -= 1;
currGold -= C.MONSTER_GOLD;
}
if (monsters[i].currentLabel == "remove")
{
mcGameStage.removeChild(monsters[i]);
monsters.splice(i,1);
//Award Gold
currGold += C.MONSTER_GOLD;
}
}
//Update all the towers
for (i in towers)
{
towers[i].update();
}
//Update all the bullets
for (i=bullets.length - 1; i >= 0; i--)
{
bullets[i].update();
if (bullets[i].currentLabel == "remove")
{
mcGameStage.removeChild(bullets[i]);
bullets.splice(i,1);
}
}
//******************
//Handle Display
//******************
//Display new Score
mcGameUI.txtLife.text = String(life);
mcGameUI.txtGold.text = String(currGold);
mcGameUI.txtWave.text = String(currWave) + " / " + String(maxWave);
//Check for end game
if (life <= 0)
{
gameOver();
//stop all subsequent code in this update to run
return;
}
else if ((currWave == maxWave) && (monsters.length == 0))
{
gameWin();
}
}
private function spawnMonster(xPos, yPos)
{
var monsterToSpawn = new Monster();
monsterToSpawn.x = xPos;
monsterToSpawn.y = yPos;
monsters.push(monsterToSpawn);
mcGameStage.addChild(monsterToSpawn);
}
private function spawnWave(currWave)
{
if (currWave == 1)
{
spawnMonster(C.MONSTER_START_X, C.MONSTER_START_Y);
}
else if (currWave == 2)
{
for (i = 0; i < 2; i++)
{
spawnMonster(C.MONSTER_START_X - 40*i, C.MONSTER_START_Y);
}
}
}
Hi I don't understand why you are getting this error, but this can help you,
try the follow code instead of Point();
var checkPoints:Array=new Array({x:85,y:140},
{x:85,y:320},
{x:325,y:320},
{x:325,y:200},
{x:265,y:200},
{x:265,y:80},
{x:505,y:80},
{x:505,y:380},
{x:630,y:380}
);

1046 AS3 Compile Time Error

I'm having major issues with this one error
//Obligitory Stop
stop();
//Imports
import flash.events.Event;
import flash.events.KeyboardEvent;
import fl.motion.easing.Back;
import flash.events.MouseEvent;
import flash.accessibility.Accessibility;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
//Variables
var bulletSpeed:uint = 20;
var scoreData:int;
var bullets:Array = new Array();
var killCounter:int;
var baddieCounter:int;
var currentLevel:int = 1;
var baddieDamage:int;
var energyCost:int;
var target:MovieClip;
var baddies:Array = new Array();
var timer:Timer = new Timer(1);
var baddieSpeed:int;
var score:int;
var levelKR:int;
var level1KR:int = 10;
var level2KR:int = 25;
var level3KR:int = 50;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var Baddie:MovieClip
var mySound:Sound = new ShootSFX();
//Level Atributes set
if (currentLevel == 1)
{
baddieSpeed = 2;
baddieDamage = 20;
timer.delay = 4000;
levelKR = level1KR;
bulletSpeed = 10;
energyCost = 50;
var energyTimer:Timer = new Timer(50);
var healthTimer:Timer = new Timer(1000);
}
//Event Listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
rbDash.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
//Timers Start
timer.start();
energyTimer.start();
healthTimer.start();
//Initialize score
Score.text = String("Level "+currentLevel+" - begin!");
//load score data
score = scoreData;
//Checks Kill Counter
checkKillCounter();
//Shoot gun on space
function fireGun(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.SPACE)
{
bullet.x = rbDash.x;
bullet.y = rbDash.y + 50;
addChild(bullet);
bullets.push(bullet);
}
}
//Move Objects
function moveObjects(evt:Event):void
{
moveBullets();
moveBaddies();
}
//Move bullets
function moveBullets():void
{
for (var i:int = 0; i < bullets.length; i++)
{
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x <-bullets[i].width
|| bullets[i].x > stage.stageWidth + bullets[i].width
|| bullets[i].y < -bullets[i].width
|| bullets[i].y > stage.stageHeight + bullets[i].width)
{
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
//Spawns Enemy
function addBaddie(evt:TimerEvent):void
{
updateScore(25);
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
}
else if (side == 2)
{
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
else if (side == 3)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
}
else if (side == 4)
{
baddie.x = - baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
baddie.speed = baddieSpeed;
addChild(baddie);
baddies.push(baddie);
baddieCounter += 1;
if (baddieCounter == levelKR)
{
timer.stop();
}
}
//Moves Enemy
function moveBaddies():void
{
for (var i:int = 0; i < baddies.length; i++)
{
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(rbDash.x,rbDash.y,true))
{
removeChild(baddies[i]);
baddies.splice(i, 1);
//HealthBar.gotoAndStop(HealthBar.currentFrame + baddieDamage);
killCounter += 1;
checkKillCounter();
//if (HealthBar.currentFrame == 100)
{
gotoAndStop(5);
}
}
else
{
checkForHit(baddies[i]);
}
}
}
//Hit detection
function checkForHit(baddie:Baddie):void {//Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
for (var i:int = 0; i < bullets.length; i++)
{
if (baddie.hitTestPoint(bullets[i].x,bullets[i].y,true))
{
removeChild(baddie);
removeChild(bullets[i]);
baddies.splice(baddie.indexOf(baddie), 1);
bullets.splice(bullets[i]);
updateScore(100);
killCounter += 1;
checkKillCounter();
}
}
}
//Updates score
function updateScore(points:int):void
{
score += points;
Score.text = String("Points: "+score);
}
//stops timers
function timerStop():void
{
timer.stop();
energyTimer.stop();
healthTimer.stop();
}
//Y axis movement
//totaly not a code snippet
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rbDash.y -= 5;
}
if (downPressed)
{
rbDash.y += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = true;
break;
};
case Keyboard.DOWN :
{
downPressed = true;
break;
}
}
};
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = false;
break;
};
case Keyboard.DOWN :
{
downPressed = false;
break;
}
}
};
//makes the deg2rad work for the bullets/enemy
function deg2rad(degree)
{
return degree * (Math.PI / 180);//Had issues with "deg2rad" functions
}
//Removes listeners
function removeAllListeners():void
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.removeEventListener(Event.ENTER_FRAME, moveObjects);
timer.removeEventListener(TimerEvent.TIMER, addBaddie);
}
//Checks if level end
function checkKillCounter():void
{
EnemiesLeft.text = ("Enemies Left: "+String(levelKR - killCounter));
if (killCounter == levelKR)
{
shutdown();
gotoAndStop(3);
}
}
//Stops everything
function shutdown():void
{
timerStop();
removeAllListeners();
removeChild(target);
}
I get Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
Thanks Guys
Im trying to get this done today so i can move on
Is Baddie a class that is in the default package? If not, you need to import it:
import packagename.Baddie;
If Baddie is a library symbol, make sure you've checked 'Export for ActionScript' and that the linkage name is correct. Also make sure that is is exported in frame 1, or at least before or on the frame that your code is on.
In you Library, right click on Baddie and choose "properties" and check "export for ActionScript". Now you can use Baddie as a class that extends MovieClip.
Sorry, I didn't notice this was already recommended. Basically, your error cannot find a Class named Baddie, hence why you need to specify the custom class through the Library instance.

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.