ADDED_TO_STAGE Event doesn't work in certain frame? - actionscript-3

This is Heli's Class and it'll called in main class ,the target of main class in frame 2 .
The frame 1 contain button that can make me go to frame 2 .but this movie clip of Heli doesn't added to the stage . but it'll work if i targeting main class in frame 1 . so can anyone tell me how to use added_to_stage event in specified frame ??? (sorry about my english)
package com.ply
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Heli extends MovieClip
{
//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;
private var bullets:Array;
private var missiles:Array;
public function Heli()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
private function init():void
{
stage.addEventListener(Event.ENTER_FRAME, runGame);
}
private function runGame(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 Heli()
{
if (stage) init();
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}

here it 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.events.Event;
import flash.events.MouseEvent;
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();
//================================================
public function Main()
{
//stage.addEventListener(Event.ENTER_FRAME, gameLoop);
// instantiate car class
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 {
//addChild(bulletholder);
addChild(bulletContainer);
gameState = STATE_START_PLAYER;
gameLoop();
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add car to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
//CheckTime();
gameLoop();
//txtScore.text = 'Score: '+score;
}
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
player.xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
player.yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 1;
}
else if (event.keyCode == 32 && shootAllow)
{
fireBullet();
}
}
public function fireBullet() {
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
var newBullet2:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = player.x+20; //+ player.width/2 - player.width/2;
newBullet.y = player.y;
newBullet2.x = player.x-20;
newBullet2.y = player.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
bulletContainer.addChild(newBullet2);
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
//if time hasn't reached the limit, then just increment
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;
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 0;
}
}
}
}

Related

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 won't fire?

I have been working on a space invaders game, I currently have no compiling errors finally but my bullets wont fire.
I kind of know where I should be looking to fix the problem but everything I try fails. Am I right in thinking it is to do with the bullet x-y argument?
I have a Movieclip symbol in the library named Bullet the same as my .as file but the script dose not seem to add the bullets to the scene.
Here is my ship and bullet code.
ship.as
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
/**
* ...
* #author Kenny Martin
*/
public class Ship extends MovieClip
{
private var fireRate:int = 6;
private var framesSinceFire:int = 0;
private var bulletHolder:Sprite
private var leftDown:Boolean = false
private var rightDown:Boolean = false
private var firing:Boolean = false
private var speed:int = 10;
private var bulletPool:Vector.<Bullet>
public function Ship(bHolder:Sprite)
{
x = 275;
y = 350;
bulletHolder = bHolder;
addEventListener(Event.ADDED_TO_STAGE, addedToStage, false, 0, true);
}
private function fillBulletPool():void
{
bulletPool = Vector.<Bullet>();
// while counter
var i:int = 0;
// while i is less than 25, keep adding bullets
while (i < 25)
{
//if we dont increase i,we risk getting stuck in an infinite loop
i++;
//push a new bullet straight into the vector
bulletPool.push(new Bullet());
}
}
public function update():void
{
// check if left is down and the ship is at least half its width from the edge
if (leftDown && x > (width / 2))
x -= speed;
// check if right is down and the ship is more than half its width from the right edge
if (rightDown && x < stage.stageWidth - (width / 2))
x += speed;
if (firing && framesSinceFire >= fireRate)
Fire();
}
public function updateBullets():void
{
framesSinceFire++;
updateBullets();
for (var i:int = 0; i < bulletPool.length; i++)
{
bulletPool[i].update();
}
}
public function Fire():void
{
var bullet:Bullet = findBullet();
if ( bullet != null)
{
bullet.activate(x,y);
bulletHolder.addChild(bullet);
framesSinceFire = 0;
}
}
private function addedToStage(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp, false, 0, true);
}
private function keyUp(e:KeyboardEvent):void
{
// check left arrow
if (e.keyCode == 37)
leftDown = false;
else if (e.keyCode == 39 ) // check right arrow]
rightDown = false;
else if ( e.keyCode == 32)// check space bar
firing = false;
}
private function keyDown(e:KeyboardEvent):void
{
// check left arrow
if (e.keyCode == 37)
leftDown = true;
else if (e.keyCode == 39 ) // check right arrow]
rightDown = true;
else if ( e.keyCode == 32)// check space bar
firing = true;
}
private function findBullet():Bullet
{
// loop through the bulletpool,from 0 to 24(we added 25 bullets to the pool)
for (var i:int = 0; i < bulletPool.length; i++)
{
if (!bulletPool[i].isActive)
{
// if its not active return the bullet for use
return bulletPool[i];
}
}
return null;
}
}
}
Bullet.as
package
{
import flash.display.MovieClip;
/**
* ...
* #author Kenny Martin
*/
public class Bullet extends MovieClip
{
public var isActive:Boolean = false
private var speed:int = 0.2;
private var _x:int;
private var _y:int;
public function Bullet()
{
super()
}
public function activate(_x:Number,_y:Number)
{
isActive = true;
x = _x;
y = _y;
}
public function deactivate():void
{
isActive = false;
// check we've got a parent before trying to remove ourselves from one
if (parent)
parent.removeChild(this);
}
public function update():void
{
if (isActive)
// move up the screen
y -= speed;
//until we go well past the top of the screen
if (y < -height)
{
deactivate();
}
}
}
}
You're not calling the updateBullets function.
The only call to updateBullets is... inside updateBullets... which is never called (and would cause a stack overflow if you did call it with a call to itself in there).
You need to move the updateBullets function call to update().

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

All my references to the stage method are throwing null reference errors in as3

I'm not sure what the change was that caused this, but suddenly i'm getting null object references in all the cases that I use the stage method as a parameter. My code is too long to fit all the different instances, so I'll just attach one or two.
package com.Mass.basics1
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
public class Main extends MovieClip
{
public var ourPlanet:Cosmo = new Cosmo(stage);
public var ourAsteroid:Asteroid = new Asteroid();
private var numStars:int = 80;
private var numAsteroids:int = 5;
public static var a:Number = 0;
private var stageRef:Stage;
//public var ourAsteroid:Asteroid = new Asteroid(stage);
//private var ourAsteroid:Asteroid = new Asteroid();
//our constructor function. This runs when an object of
//the class is created
public function Main()
{
//create an object of our ship from the Ship class
stop();
//add it to the display list
stage.addChild(ourPlanet);
ourPlanet.x = stage.stageWidth / 2;
ourPlanet.y = stage.stageHeight / 2;
this.stageRef = stageRef;
for (var i:int = 0; i < numStars; i++)
{
stage.addChildAt(new Star(stage), stage.getChildIndex(ourPlanet));
}
for (var o:int = 0; o < numAsteroids; o++)
{
stage.addChildAt(new Asteroid(), stage.getChildIndex(ourPlanet));
}
My debugger tells me there is a null object reference at line 13, and this code is from my engine. Cosmo is another external file that is linked to a symbol. I'll post the code from there, but there are about 4 of these errors across 4 different .as files, but it'd be too much code to put in here, so I'll just add from one other file I think would be important.
Code From Cosmo.as
package com.Mass.basics1
{
import flash.display.MovieClip;
import flash.display.Stage;
import com.senocular.utils.KeyObject;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.text.TextField;
public class Cosmo extends MovieClip
{
private var stageRef:Stage;
private var key:KeyObject;
private var speed:Number = 20;
private var vx:Number = 0;
private var vy:Number = 0;
private var friction:Number = 0.93;
private var maxspeed:Number = 8;
public var destroyed:Boolean = false;
public function Cosmo(stageRef:Stage)
{
this.stageRef = stageRef;
var key:KeyObject = new KeyObject(stage);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
public function loop(e:Event) : void
{
//keypresses
if (key.isDown(Keyboard.A))
vx -= speed;
else if (key.isDown(Keyboard.D))
vx += speed;
else
vx *= friction;
if (key.isDown(Keyboard.W))
vy -= speed;
else if (key.isDown(Keyboard.S))
vy += speed;
else
vy *= friction;
//update position
x += vx;
y += vy;
//speed adjustment
if (vx > maxspeed)
vx = maxspeed;
else if (vx < -maxspeed)
vx = -maxspeed;
if (vy > maxspeed)
vy = maxspeed;
else if (vy < -maxspeed)
vy = -maxspeed;
//ship appearance
rotation = vx;
scaleX = (maxspeed - Math.abs(vx))/(maxspeed* 4) + 0.75;
//stay inside screen
if (x > stageRef.stageWidth)
{
x = stageRef.stageWidth;
vx = -vx;
}
else if (x < 0)
{
x = 0;
vx = -vx;
}
if (y > stageRef.stageHeight)
{
y = stageRef.stageHeight;
vy = -vy;
}
else if (y < 0)
{
y = 0;
vy = -vy;
}
}
}
}
I'm also getting an error here at line 26 for the same thing.
Code from another file
package com.senocular.utils {
import flash.display.Stage;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* The KeyObject class recreates functionality of
* Key.isDown of ActionScript 1 and 2
*
* Usage:
* var key:KeyObject = new KeyObject(stage);
* if (key.isDown(key.LEFT)) { ... }
*/
dynamic public class KeyObject extends Proxy {
private static var stage:Stage;
private static var keysDown:Object;
public function KeyObject(stage:Stage) {
construct(stage);
}
public function construct(stage:Stage):void {
KeyObject.stage = stage;
keysDown = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
flash_proxy override function getProperty(name:*):* {
return (name in Keyboard) ? Keyboard[name] : -1;
}
public function isDown(keyCode:uint):Boolean {
return Boolean(keyCode in keysDown);
}
public function deconstruct():void {
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
keysDown = new Object();
KeyObject.stage = null;
}
private function keyPressed(evt:KeyboardEvent):void {
keysDown[evt.keyCode] = true;
}
private function keyReleased(evt:KeyboardEvent):void {
delete keysDown[evt.keyCode];
}
}
}
In this file, i'm getting errors at lines 23 and 29. Thanks in advance, let me know if you need more information of any kind.
The stage property is going to be null until added to the display list hierarchy of the stage. You can't add the object to the stage until after the constructor is executed, so therefore you won't ever be able to access stage in the constructor. It's going to be null.
Call the construct method after creating the instance and adding it to the stage's display list hierarchy.

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