AS3 Generating differnet Enemies and bullets hitTest Problems - actionscript-3

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
}

Related

How can I change Nested Class in actionscript 3

I'm working off an actionscript 3 code that pulls information from other actionscript 3's. The main code is Herbfight and it references 4 others (Bullets, bugs, Goodbugs and Sprayer). Below I'm trying to combine them all into one actionscript. The reason for this is that I want to pull it in as a symbol rather then having the flash file relate to the class.
The problem is it says I can't have nested classes. Any thoughts on how i can fix this? Below is my attempt to combine the code.
Thanks,
J
package {
import flash.display.;
import flash.events.;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.*;
import flash.utils.getTimer;
import flash.geom.Point;
public class herbfight_v004 extends MovieClip {
private var aagun:Sprayer;
private var airplanes:Array;
private var goodbug:Array;
private var bullets:Array;
private var upArrow, downArrow:Boolean;
private var nextPlane:Timer;
private var nextGbugs:Timer;
private var shotsLeft:int;
private var shotsHit:int;
private var Sprayer:MovieClip
private var Bullets:MovieClip
private var bugs:MovieClip
private var GooodBugs:MovieClip
public function startherbfight_v004() {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
// create gun
aagun = new Sprayer();
addChild(aagun);
// create object arrays
airplanes = new Array();
bullets = new Array();
goodbug = new Array();
// listen for keyboard
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// look for collisions
addEventListener(Event.ENTER_FRAME,checkForHits);
// start planes flying
setNextPlane();
setNextGbugs();
public function Sprayer() {
{
// animation time// initial location of gun
this.x = 410;
this.y = 380;
// movement
addEventListener(Event.ENTER_FRAME,moveGun);
}
public function moveGun(event:Event) {
// get time difference
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// current position
var newy = this.y;
// move to the left
if (MovieClip(parent).upArrow) {
newy -= speed*timePassed/1000;
}
// move to the right
if (MovieClip(parent).downArrow) {
newy += speed*timePassed/1000;
}
// check boundaries
if (newy < 65) newy = 65;
if (newy > 380) newy = 380;
// reposition
this.y = newy;
}
// remove from screen and remove events
public function deleteGun() {
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveGun);
}
}
public function bugs(side:String, speed:Number, altitude:Number) {
{
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = 1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = 1; // not reverse
}
this.y = altitude; // vertical position
// choose a random plane
this.gotoAndStop(Math.floor(Math.random()*4+1));
// set up animation
addEventListener(Event.ENTER_FRAME,movePlane);
lastTime = getTimer();
}
public function movePlane(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move plane
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deletePlane();
} else if ((dx > 0) && (x > 350)) {
deletePlane();
}
}
// plane hit, show explosion
public function planeHit() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
gotoAndPlay("explode");
}
// delete plane from stage and plane list
public function deletePlane() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
parent.removeChild(this);
}
}
public function Bullets(x,y:Number, speed: Number) {
{
// set start position
this.x = x;
this.y = y;
// get speed
dx = speed;
// set up animation
lastTime = getTimer();
addEventListener(Event.ENTER_FRAME,moveBullet);
}
public function moveBullet(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move bullet
this.x += dx*timePassed/1000;
// bullet past top of screen
if (this.x < 0) {
deleteBullet();
}
}
// delete bullet from stage and plane list
public function deleteBullet() {
MovieClip(parent).removeBullet(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveBullet);
}
}
public function GoodBugs(side:String, speed:Number, altitude:Number) {
{
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = -1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = -1; // not reverse
}
this.y = altitude; // vertical position
// choose a random Gbugs
this.gotoAndStop(Math.floor(Math.random()*2+1));
// set up animation
addEventListener(Event.ENTER_FRAME,moveGbugs);
lastTime = getTimer();
}
public function moveGbugs(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move Gbugs
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deleteGbugs();
} else if ((dx > 0) && (x > 350)) {
deleteGbugs();
}
}
// Gbugs hit, show explosion
public function GbugsHit() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
gotoAndPlay("explode");
}
// delete Gbugs from stage and Gbugs list
public function deleteGbugs() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
parent.removeChild(this);
}
}
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
if (Math.random() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
var speed:Number = Math.random()*150+150;
// create plane
var p:bugs = new bugs(side,speed,altitude);
addChild(p);
airplanes.push(p);
// set time for next plane
setNextPlane();
}
public function setNextGbugs() {
nextGbugs = new Timer(1000+Math.random()*1000,1);
nextGbugs.addEventListener(TimerEvent.TIMER_COMPLETE,newGbugs);
nextGbugs.start();
}
public function newGbugs(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
var speed:Number = Math.random()*150+150;
// create Gbugs
var p:GoodBugs = new GoodBugs(side,speed,altitude);
addChild(p);
goodbug.push(p);
// set time for next Gbugs
setNextGbugs();
}
// check for collisions
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=airplanes.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(airplanes[airplaneNum])) {
airplanes[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
shotsHit++;
showGameScore();
break;
}
}
}
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var GoodBugsNum:int= goodbug.length-1; GoodBugsNum>=0; GoodBugsNum--) {
if (bullets[bulletNum].hitTestObject(goodbug [GoodBugsNum])) {
goodbug [GoodBugsNum]. GbugsHit();
bullets[bulletNum].deleteBullet();
shotsHit--;
showGameScore();
break;
}
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
// key pressed
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = true;
} else if (event.keyCode == 40) {
downArrow = true;
} else if (event.keyCode == 32) {
fireBullet();
}
}
// key lifted
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = false;
} else if (event.keyCode == 40) {
downArrow = false;
}
}
// new bullet created
public function fireBullet() {
if (shotsLeft <= 0) return;
var b:Bullets = new Bullets(aagun.x,aagun.y,-300);
addChild(b);
bullets.push(b);
shotsLeft--;
showGameScore();
}
public function showGameScore() {
showScore.text = String("Score: "+shotsHit);
showShots.text = String("Shots Left: "+shotsLeft);
}
// take a plane from the array
public function removePlane(plane:bugs) {
for(var i in airplanes) {
if (airplanes[i] == plane) {
airplanes.splice(i,1);
break;
}
}
}
// take a plane from the array
public function removeGbugs(Gbugs:GoodBugs) {
for(var i in goodbug) {
if (goodbug[i] == Gbugs) {
goodbug.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullets) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
// game is over, clear movie clips
public function endGame() {
// remove planes
for(var i:int=airplanes.length-1;i>=0;i--) {
airplanes[i].deletePlane();
}
for(var i:int= goodbug.length-1;i>=0;i--) {
goodbug [i].deleteGbugs();
}
airplanes = null;
goodbug = null
aagun.deleteGun();
aagun = null;
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
removeEventListener(Event.ENTER_FRAME,checkForHits);
nextPlane.stop();
nextPlane = null;
nextGbugs.stop();
nextGbugs = null;
gotoAndStop("gameover");
}
}
}

How do I call methods and properties from parent classes?

I'm new here (and also relatively new with AS3 as well), so bear with me.
I've only discovered OOP 2 weeks ago, and before then, I knew only the most rudimentary knowledge of AS3. So I did make a lot of improvement, but one thing's been bugging me.
I can never seem to call functions and methods from parent classes. Even with setters and getters, the child class always gives me an output error. It looks something like this.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Axiom/clicked()
This is an AS3 project that I'm working on right now that is giving me this problem.
Here's some basic background of the project.
I have the main class, called Main, and some other classes, called Axiom and Textbox. Main creates Axiom into a movieclip (background) that's already present on the stage. Axiom creates Textbox when clicked. Axiom calls a method called mouseClick from Main (plays a sound), and Textbox calls some properties from Axiom (text for the textbox).
I have attempted to use
MovieClip(this.parent).mouseClick();
and declaring a new variable in the child class, like this.
private var main:Main;
...
main.mouseClick();
And this leads me to question - what am I doing wrong, and how should I do it properly?
Here are the classes for reference.
Main.as
package {
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Mouse;
import flash.events.MouseEvent;
public class Main extends MovieClip {
// sound
private var music:Music = new Music();
private var clickSound:Click = new Click();
// instructions
private var instructions:Instructions = new Instructions();
// mouse
private var cursor:Cursor = new Cursor();
// player
private var player:Player = new Player();
private var animationState:String = "standing";
private var directionState:String = "right";
// Axiom
private var axiom:Axiom = new Axiom();
// movement
private var rightPressed:Boolean = false;
private var leftPressed:Boolean = false;
private var upPressed:Boolean = false;
private var downPressed:Boolean = false;
private var xMovement:Number = 0;
private var yMovement:Number = 0;
private var speed:Number = 22;
private var friction:Number = 0.9;
private var rDoubleTapCounter:int = 0;
private var lDoubleTapCounter:int = 0;
private var dDoubleTapCounter:int = 0;
private var uDoubleTapCounter:int = 0;
private var doubleTapCounterMax:int = 5;
private var running:Boolean = false;
public function Main() {
// constructor code
// mouse
stage.addChild(cursor);
cursor.mouseEnabled = false;
Mouse.hide();
// instructions
instructions.x = 640;
instructions.y = 120;
stage.addChild(instructions);
// add player
player.x = 642;
player.y = 448.95;
player.gotoAndStop(directionState);
player.right.gotoAndStop(animationState);
addChild(player);
// add Axiom
axiom.x = 300;
axiom.y = -150;
back.addChild(axiom);
// keyboard events
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
// music
music.play(0, int.MAX_VALUE);
// loop
stage.addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(e:Event):void {
// set mouse
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
// set Movement to speed
if (rightPressed) {
if (upPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * -2;
} else {
xMovement = speed;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * 2;
} else {
xMovement = speed;
yMovement = speed;
}
} else if (running || rDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * 2;
} else {
xMovement = speed;
}
} else if (leftPressed) {
if (upPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * -2;
} else {
xMovement = speed * -1;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * 2;
} else {
xMovement = speed * -1;
yMovement = speed;
}
} else if (running || lDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * -2;
} else {
xMovement = speed * -1;
}
} else if (downPressed) {
if (dDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
} else if (upPressed) {
if (uDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
}
// double tap counter
if (rightPressed == false) {
rDoubleTapCounter++;
}
if (leftPressed == false) {
lDoubleTapCounter++;
}
if (downPressed == false) {
dDoubleTapCounter++;
}
if (upPressed == false) {
uDoubleTapCounter++;
}
// change labels
if (player.currentLabel != animationState) {
player.right.gotoAndStop(animationState);
}
// friction
xMovement *= friction;
yMovement *= friction;
// animationState and stop
if (Math.abs(xMovement) > 1) {
if (Math.abs(xMovement) > 22) {
animationState = "running";
running = true;
} else {
animationState = "trotting";
running = false;
}
} else {
animationState = "standing";
xMovement = 0;
}
// right or left facing
if (xMovement > 0) {
player.scaleX = 1;
} else if (xMovement < 0) {
player.scaleX = -1;
}
//movement
if (back.x >= back.width / 2 - 50) {
if (player.x >= 642 && xMovement > 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x <= player.width / 2 && xMovement < 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else if (back.x <= 1280 - back.width / 2 + 50) {
if (player.x <= 642 - 30 && xMovement < 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x >= 1280 + 30 - player.width / 2 && xMovement > 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else {
back.x -= xMovement;
}
}
private function keyPressed(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = true;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = true;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = true;
} else if (e.keyCode == Keyboard.UP) {
upPressed = true;
}
}
private function keyReleased(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = false;
rDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = false;
lDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = false;
dDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.UP) {
upPressed = false;
uDoubleTapCounter = 0;
}
}
public function mouseClick():void {
clickSound.play();
}
}
}
Axiom.as
package {
import flash.events.MouseEvent;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main;
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
main.mouseClick();
stage.addChild(speechBox);
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
Textbox.as
package {
import flash.events.MouseEvent;
import flash.display.MovieClip;
import com.greensock.TweenLite;
public class Textbox extends MovieClip{
private var axiom:Axiom;
private var main:Main;
public function Textbox() {
// constructor code
this.x = 40;
this.y = 360;
this.textBox.text = axiom.words;
TweenLite.from(this, 0.3, {x: "10", alpha: 0});
this.addEventListener(MouseEvent.CLICK, nextPage);
}
private function nextPage(e:MouseEvent):void{
main.mouseClick();
TweenLite.to(this, 0.3, {x: "-10", alpha: 0});
MovieClip(this.parent).removeThis();
}
}
}
Instead of trying to call functions of the parent (rarely a good idea), use Events instead.
In your Axiom Class:
package {
...import statements
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main; //this shouldn't be here, ideally, Axiom knows NOTHING about the main class.
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
//main.mouseClick(); // unneccesary
dispatchEvent(e); //the event you caught by performing a click will be dispatched again, so that the parent can react to it
stage.addChild(speechBox); //Axiom might not have access to the stage, addChild would suffice
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
and in your Main Class
axiom.addEventListener(MouseEvent.CLICK, onAximClicked);
private function onAxiomClicked(e:MouseEvent):void{
//now you can use the parents (in this case an Object of the Main class) functions
mouseClick();
}

Bullet fires perfectly in three directions, but not left

I'm quite new with actionscript, and have been scrapping together a little test game to sort of get used to the language, get my feet wet. The premise behind the game is pretty average, I have a character that can move in 8 directions, can pick up several keys that are randomly placed, and open a door when he possesses a key.
The problem comes in to play with the bullet shooting. I don't know much about trigonometry, so when a key is pressed, i just use the .rotate property to turn the player. I pass the .rotate integer into my bullet class and use that to tell which direction the bullet should travel. It works perfectly for the up, down, and right movements, but when the character is facing left the bullet is created but has no velocity whatsoever, and for the life of me I cannot figure out where the error in the code is.
If someone could look over my code and help me out, I would be much appreciated. I'm sure it's something simple that I'm just missing. I know it's a bit sloppy, so if there's any other tips you want to pass on to a novice please feel free!!
Thank you so much guys.
Main Class
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.text.TextField;
public class Main extends MovieClip
{
var player:Player;
var inventory:Inventory;
var invArray:Array = new Array();
var key:_Key;
var vx:int;
var maxSpeed:int;
var key_Up:Boolean;
var key_Down:Boolean;
var key_Left:Boolean;
var key_Right:Boolean;
var maxKey:int;
var keyCount:TextField;
var keysUp:int;
var door:Door;
var doorOpen:Boolean;
var wall1:Wall;
var wall2:Wall;
var wallCollide:Boolean;
var bulletTime:int;
var bulletLimit:int;
var bulletShoot:Boolean;
static var playerRotation:int;
public function Main()
{
init();
}
public function init():void
{
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
initPlayer();
initVariables();
initInventory();
initItems();
}
public function gameLoop(e:Event):void
{
movePlayer();
collisionDetection();
bullet();
}
public function keyDownHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37 :
key_Left = true;
break;
case 38 :
key_Up = true;
break;
case 39 :
key_Right = true;
break;
case 40 :
key_Down = true;
break;
case 32:
if(bulletShoot)
{
bulletShoot = false;
var newBullet:Bullet = new Bullet(player.rotation);
newBullet.x = player.x;
newBullet.y = player.y;
addChild(newBullet);
}
}
}
public function keyUpHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37 :
key_Left = false;
break;
case 38 :
key_Up = false;
break;
case 39 :
key_Right = false;
break;
case 40 :
key_Down = false;
break;
}
}
public function movePlayer():void
{
if (key_Left && !key_Right)
{
player.x -= maxSpeed;
player.rotation = 270;
}
if (key_Right && !key_Left)
{
player.x += maxSpeed;
player.rotation = 90;
}
if (key_Up && !key_Down)
{
player.y -= maxSpeed;
player.rotation = 0;
}
if (key_Down && !key_Up)
{
player.y += maxSpeed;
player.rotation = 180;
}
/*if ( key_Left && key_Up && !key_Right && !key_Down )
{
player.rotation = 315;
}
if ( key_Right && key_Up && !key_Left && !key_Down )
{
player.rotation = 45;
}
if ( key_Left && key_Down && !key_Right && !key_Up )
{
player.rotation = 225;
}
if ( key_Right && key_Down && !key_Left && !key_Up )
{
player.rotation = 135;
}*/
}
public function initPlayer():void
{
player = new Player();
player.x = stage.stageWidth * .5;
player.y = stage.stageHeight * .5;
stage.addChild(player);
}
public function initVariables():void
{
vx = 0;
maxSpeed = 4;
key_Up = false;
key_Down = false;
key_Left = false;
key_Right = false;
maxKey = 3;
keysUp = 0;
doorOpen = false;
wallCollide = false;
bulletTime = 0;
bulletLimit = 12;
bulletShoot = true ;
}
public function collisionDetection():void
{
for (var i:int=0; i < invArray.length; i++)
{
key = invArray[i];
if (player.hitTestObject(key))
{
stage.removeChild(key);
invArray.splice(i, 1);
keysUp++;
//trace(keysUp);
i--;
keyCount.text = String(keysUp);
break;
}
}
if (player.hitTestPoint(door.x,door.y + 25,true) && (keysUp > 0) && ! doorOpen)
{
door.gotoAndStop(2);
keysUp--;
invArray.pop();
trace(keysUp);
keyCount.text = String(keysUp);
doorOpen = true;
}
if (player.hitTestObject(door) && (keysUp == 0) && ! doorOpen)
{
wallCollide = true;
}
if (player.hitTestObject(wall1))
{
wallCollide = true;
}
if (player.hitTestObject(wall2))
{
wallCollide = true;
}
if (wallCollide == true)
{
player.y += 4;
wallCollide = false;
}
}
public function initInventory():void
{
inventory = new Inventory();
inventory.x = stage.stageWidth * .15;
inventory.y = stage.stageHeight * .90;
stage.addChild(inventory);
keyCount = new TextField();
stage.addChild(keyCount);
keyCount.x = inventory.x - 8;
keyCount.y = inventory.y + 3;
keyCount.text = String(keysUp);
//keyCount.border = true;
keyCount.width = 20;
keyCount.height = 20;
}
public function initItems():void
{
while (invArray.length < maxKey)
{
key = new _Key ;
key.x = Math.random() * 550;
key.y = Math.random() * 300;
stage.addChild(key);
invArray.push(key);
}
door = new Door();
door.x = 250;
door.y = 25;
wall1 = new Wall();
stage.addChild(wall1);
wall1.x = door.x - 175;
wall1.y = door.y;
wall2 = new Wall();
stage.addChild(wall2);
wall2.x = door.x + 175;
wall2.y = door.y;
stage.addChild(door);
}
public function bullet():void
{
if (bulletTime < bulletLimit)
{
bulletTime++;
} else
{
bulletShoot = true;
bulletTime = 0;
}
}
}
}
Bullet Class
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip {
public var _root:Object;
public var speed:int = 10;
public var bulletRotation:int;
public function Bullet(pRotation:int) {
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, eFrame);
bulletRotation = pRotation;
}
private function beginClass(e:Event):void
{
_root = MovieClip(root);
}
private function eFrame(e:Event):void
{
if (bulletRotation == 0)
{
this.y -= speed;
}
else if (bulletRotation == 90)
{
this.x += speed;
}
else if(bulletRotation == 270)
{
this.x -= speed;
}
else if(bulletRotation == 180)
{
this.y += speed;
}
if(this.y < -1 * this.height)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
}
if(this.x < -1 * this.width)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
}
}
}
}
In Bullet class, change 270 to -90, at line 38:
else if(bulletRotation == -90)
{
this.x -= speed;
}

ActionScript 3 Cant see Movieclip

When I play my game it does not show my _Player Movieclip, but it does collide with the ground which is very confusing. So I believe the movieclip is there but not showing the texture/Sprite.
I think the problem is in "function Spawn" (First Function).
public class PewdyBird extends MovieClip
{
//Player variables
public var Up_Speed:int = 25;
public var speed:Number = 0;
public var _grav:Number = 0.5;
public var isJump:Boolean = false;
public var Score:int = 0;
public var Player_Live:Boolean = true;
public var _Player:Player = new Player();
//Other variables
//Environment variables
var Floor:int = 480;
var Clock:Number = 0;
var Clock_restart:Number = 0;
var Clock_ON:Boolean = false;
var Clock_max:int = 15;
var Player_Stage:Boolean = true;
private var _X:int;
private var _Y:int;
private var hit_ground:Boolean = false;
private var width_BG:int = 479;
//SPAWN
function Spawn(e:Event){
_Player.x = 200;
_Player.y = 200;
stage.addChild(_Player);
}
//Keyboard Input
private function KeyboardListener(e:KeyboardEvent){
if(e.keyCode == Keyboard.SPACE){
Clock = Clock_restart;
Clock_ON = true;
isJump = true;
if(isJump){
_Player.gotoAndPlay("Fly");
speed = -Up_Speed;
isJump = false;
}
}
}
//Mouse Input & Spawn Listener
private function MouseListener(m:MouseEvent){
if(MouseEvent.CLICK){
Clock = Clock_restart;
Clock_ON = true;
isJump = true;
if(isJump){
_Player.gotoAndPlay("Fly");
speed = -Up_Speed;
isJump = false;
}
}
}
//Rotation Fly
function Rot_Fly(){
if(Clock < Clock_max){
_Player.rotation = -15;
}else if(Clock >= Clock_max){
if(_Player.rotation < 90){
_Player.rotation += 10;
}else if(_Player.rotation >= 90){
_Player.rotation = 90;
}
}
}
//END
//Update Function
function enter_frame(e:Event):void{
Rot_Fly();
//Clock
if(Clock_ON){
Clock++;
}else if(Clock > Clock_max){
Clock = Clock_max;
}
//Fall Limits
if(speed >= 20){
_Player.y += 20;
return;
_Player.gotoAndPlay("Fall");
}
//Physics
speed += _grav*3;
_Player.y += speed;
}
//Hit Ground
function Hit_Ground(e:Event){
if(_Player.hitTestObject(Ground1)){
_grav = 0;
speed = 0;
trace("HIT GROUND");
}else if(_Player.hitTestObject(Ground2)){
_grav = 0;
speed = 0;
trace("HIT GROUND");
}else if(_Player.hitTestObject(Ground1) == false){
_grav = 1;
}else if(_Player.hitTestObject(Ground2) == false){
_grav = 1;
}
}
//Background Slide (Left)
private function Background_Move(e:Event):void{
Background1.x -= 1.5;
Background2.x -= 1.5;
Ground1.x -= 4;
Ground2.x -= 4;
if(Background1.x < -width_BG){
Background1.x = width_BG;
} else if(Background2.x < -width_BG){
Background2.x = width_BG;
} else if(Ground1.x < -width_BG){
Ground1.x = width_BG;
} else if(Ground2.x < -width_BG){
Ground2.x = width_BG;
}
}
}
The eventListeners are in flash it self
stage.addEventListener(Event.ENTER_FRAME, enter_frame);
stage.addEventListener(Event.ENTER_FRAME, Hit_Ground);
stage.addEventListener(KeyboardEvent.KEY_UP, KeyboardListener);
stage.addEventListener(MouseEvent.CLICK, MouseListener);
stage.addEventListener(Event.ENTER_FRAME, Background_Move);
stage.addEventListener(Event.ADDED_TO_STAGE, Spawn);
Player.as
package
{
import flash.display.MovieClip;
public class Player extends MovieClip
{
public function Player()
{
super();
}
}
}
Check if the movie clip's class in the library (AS3 linkage) matches the name of your player class. Also, if PewdyBird is your document class, you can move the ADDED_TO_STAGE event in the constructor. Something, like:
public function PedwyBird() {
if (stage) {
initStage();
} else {
addEventListener(Event.ADDED_TO_STAGE, initStage);
}
}
And then you can call the spawn function in the initStage function, along with adding all the event listeners. You could also have one enter frame function instead of three.
private function initStage(e:Event = null){
Spawn(); //of course, you have to remove the e:Event from Spawn declaration
stage.addEventListener(Event.ENTER_FRAME, enter_frame);
stage.addEventListener(Event.ENTER_FRAME, Hit_Ground);
stage.addEventListener(KeyboardEvent.KEY_UP, KeyboardListener);
stage.addEventListener(MouseEvent.CLICK, MouseListener);
stage.addEventListener(Event.ENTER_FRAME, Background_Move);
}

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);