As3: removing programmatically added child on hit test gives error #1009 - actionscript-3

I have tried removing programatically added movieclips when they collide with a certain object. When they do, they vanish. But after they have vanished, I get a #1009 error.
The error points at line 95, which is
if (this.x > stage.stageWidth + 2 - (stage.stageWidth - (this.width /2)) && this.x < stage.stageWidth - (this.width /2))"
And sometimes at 59, which is
if (this.x >= stage.stageWidth - 20)"
Why does it keep trying to run line 95 (and sometimes) 59? I removed the eventlistener.
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.utils.*;
public class Worker extends MovieClip
{
private var _root:MovieClip;
private var actualRange:Number;
private var reachedGoal:Boolean = false;
private var b:uint;
private var destination:Number;
private var goRight:Boolean = true;
private var goNowhere:Boolean = true;
private var yDir:Number;
private var yNumber:Number;
public function Worker()
{
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, loop);
//defining _root as the document root
actualRange =(Math.floor(Math.random() * (520 - 80 + 1)) + 80);
b = setInterval(startInc, 3000);
}
private function beginClass(event:Event):void{
//defining _root as the document root
_root = MovieClip(root);
}
private function loop(event:Event):void
{
if (this.hitTestObject(_root.killGun))
{
{
removeEventListener(Event.ENTER_FRAME, loop);
_root.removeChild(this);
}
}
if (reachedGoal == true)
{
if (goNowhere == true)
{
gotoAndStop(1);
}
//Boundaries
if (this.x <= 20)
{
goRight = true;
goNowhere = false;
}
if (this.x >= stage.stageWidth - 20)
{
goRight = false;
goNowhere = false;
}
if (this.y >= stage.stageHeight - 20)
{
yDir = 0
}
if (this.y <= 20)
{
yDir = 1
}
}
//Intro walk
if (reachedGoal == false)
{
if (this.x < actualRange)
{
gotoAndStop(4);
this.x += 3
}
if (this.x >= actualRange)
{
reachedGoal = true;
gotoAndStop(1);
}
}
//Main walk
if (this.x > stage.stageWidth + 2 - (stage.stageWidth - (this.width /2)) && this.x < stage.stageWidth - (this.width /2))
{
if (goNowhere == false)
{
if (goRight == true)
{
this.x += 1;
gotoAndStop(2);
//Y value
}
if (goRight == false)
{
if (this.x < stage.stageWidth - this.width /2)
this.x -= 1
gotoAndStop(3);
//Y value
if (yNumber == 1)
{
if(yDir == 0)
{
this.y -= 1;
}
if (yDir == 1)
{
this.y += 1;
}
}
}
}
}
}
//Timer functions
private function completePlay()
{
clearInterval(b);
}
private function startInc()
{
var moveNumber:Number = Math.floor(Math.random() * 20);
if (moveNumber == 1)
{
destination = Math.floor(Math.random() * 50);
yDir = Math.floor(Math.random() * 2);
yNumber = Math.floor(Math.random() * 4);
goRight = true;
goNowhere = false;
}
else if (moveNumber == 2)
{
destination = Math.floor(Math.random() * 50);
yDir = Math.floor(Math.random() * 2);
yNumber = Math.floor(Math.random() * 4);
goRight = false;
goNowhere = false;
gotoAndStop(3);
}
else
{
goNowhere = true;
}
}
//End
}
}

The error is happening because you're removing the eventListener within the eventListener's function and your removing the object from it's parent and still processing data that the object no longer contains or has been nullified. You should add a boolean to tell if the hitTest has occured and then not process any more of the loop. For instance:
private function loop(event:Event):void
{
var objectHit:Boolean = false;
objectHit = this.hitTestObject(_root.killGun);
if(!objectHit) {
if (reachedGoal == true)
{
if (goNowhere == true)
{
gotoAndStop(1);
}
//Boundaries
if (this.x <= 20)
{
goRight = true;
goNowhere = false;
}
if (this.x >= stage.stageWidth - 20)
{
goRight = false;
goNowhere = false;
}
if (this.y >= stage.stageHeight - 20)
{
yDir = 0
}
if (this.y <= 20)
{
yDir = 1
}
}
//Intro walk
if (reachedGoal == false)
{
if (this.x < actualRange)
{
gotoAndStop(4);
this.x += 3
}
if (this.x >= actualRange)
{
reachedGoal = true;
gotoAndStop(1);
}
}
}
if (objetHit)
{
removeEventListener(Event.ENTER_FRAME, loop);
_root.removeChild(this);
}
}
You should also remove the Event.ADDED listener once the object has been added.
private function beginClass(event:Event):void{
//defining _root as the document root
_root = MovieClip(root);
this.removeEventListener(Event.ADDED, beginClass);
}

Could it be that the rest of the loop is trying to run still?
Try breaking out of the loop after the hit:
if (this.hitTestObject(_root.killGun))
{
removeEventListener(Event.ENTER_FRAME, loop);
_root.removeChild(this);
return;
}

Related

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

Signals Keyboard Movement AS3

I'm trying to get my keyboard movement to work using signals and a Hero class. So far I can get the signal to dispatch but I can't get it to take the keyboard input. Should I be using signals for movement at all or should I just call the function from the Hero class.
This is the code for Hero:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import org.osflash.signals.Signal;
import flash.events.Event;
import com.natejc.input.KeyboardManager;
import com.natejc.input.KeyCode;
/**
* ...
* #author Kevin Raskell
*/
public class Hero extends MovieClip
{
public var defeatedSignal :Signal = new Signal();
public var _nHeroMovement :Number = 5;
public var moveSignal :Signal;
public function Hero()
{
super();
this.mouseChildren = false;
this.mouseEnabled = false;
this.addEventListener(Event.ENTER_FRAME, heroMovement);
moveSignal = new Signal();
}
public function heroDefeated()
{
trace("You have died");
}
public function heroMovement($e:Event):void
{
moveSignal.dispatch();
if (this)
{
if (KeyboardManager.instance.isKeyDown(KeyCode.DOWN))
{
if (this.y + this.height > this.stage.stageHeight || this.y - this.height <= 0)
{
this.y += -15;
this.gotoAndPlay("Idle");
return;
}
this.y += _nHeroMovement;
this.gotoAndPlay("Down");
}
else if (KeyboardManager.instance.isKeyDown(KeyCode.UP))
{
if (this.y + this.height > this.stage.stageHeight || this.y - this.height <= 0)
{
this.y += 15;
this.gotoAndPlay("Idle");
return;
}
this.y -= _nHeroMovement;
this.gotoAndPlay("Up");
}
if (KeyboardManager.instance.isKeyDown(KeyCode.LEFT))
{
if (this.x + this.width > this.stage.stageWidth || this.x - this.width <= 0)
{
this.x += 15;
this.gotoAndPlay("Idle");
return;
}
this.x -= _nHeroMovement;
this.gotoAndPlay("Left");
}
else if (KeyboardManager.instance.isKeyDown(KeyCode.RIGHT))
{
if (this.x + this.width > this.stage.stageWidth || this.x - this.width <= 0)
{
this.x += -15;
this.gotoAndPlay("Idle");
return;
}
this.x += _nHeroMovement;
this.gotoAndPlay("Right");
}
}//end if
}//end heroMovement
}//end Hero
}//end package
This is in the main function:
this.mcHero.moveSignal.add(moveHero);
}
private function moveHero():void
{
trace("Testing" + count);
count++;
}
The counting was for testing purposes for myself to see what was happening.

AS3: Child object not displaying even when added

Ok, let me start off by saying that this is my first AS3 project. I'm ok with Java, so OOP and inheritance aren't new to me.
I have literally spent hours sitting here and pondering why my code isn't working like I wanted it to.
I'm starting off with a turret trying to shoot a bullet. However, the bullet isn't being drawn onto the screen, even though the x and y coords are still changing.
The method where the bullet/projectile is created is called OnMouseClick.
Here's my code:
public class Main extends Sprite
{
public var projectileArr : Array = new Array(); //array which the projectile objects are stored
public var projCount : Number = 0; //projectile counter
public var curX:Number; //mouse coords
public var curY:Number;
private var tri1:Sprite = new Sprite();
private var tri1Height:Number = 50;
private var rect1:Sprite = new Sprite();
private var rect1W:Number = 2;
private var rect1H:Number = 10;
private var angle:Number = 0;
private var acceleration:Number = 0;
public var triSpeedX:Number = 0;
public var triSpeedY:Number = 0;
public var turretAngle:Number ;
//keyboard booleans
private var leftDown:Boolean = false, rightDown:Boolean = false, upDown:Boolean = false, downDown:Boolean = false;
public function Main():void
{
if (stage)
init();
else
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
//draw triangle
addChild(tri1);
tri1.graphics.lineStyle(1, 0xff00ff00);
tri1.graphics.beginFill(0xff0000);
tri1.graphics.moveTo(0, -tri1Height / 2)
tri1.graphics.lineTo(tri1Height / 3, +tri1Height / 2);
tri1.graphics.lineTo(-tri1Height / 3, +tri1Height / 2);
tri1.graphics.endFill();
tri1.x = 400;
tri1.y = 300;
//draw turret
addChild(rect1);
rect1.graphics.beginFill(0xFFFFFF);
rect1.graphics.moveTo(rect1W / 2, -rect1H);
rect1.graphics.lineTo(rect1W / 2, 0);
rect1.graphics.lineTo(-rect1W / 2, 0);
rect1.graphics.lineTo(-rect1W / 2, -rect1H);
rect1.graphics.endFill();
rect1.x = tri1.x;
rect1.y = tri1.y;
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(Event.ENTER_FRAME, Run);
stage.addEventListener(MouseEvent.MOUSE_MOVE, getMouseCoord);
stage.addEventListener(MouseEvent.MOUSE_DOWN, OnMouseClick);
}
//creation of projectile on click
public function OnMouseClick (e:MouseEvent):void
{
projectileArr[projCount] = new Projectile (rect1.x, rect1.y, turretAngle); //create a new projectile object
addChild(projectileArr [projCount]); //... then it doesn't display
projCount++;
trace ("BAM");
}
public function getMouseCoord(e:MouseEvent):void
{
curX = mouseX;
curY = mouseY;
}
public function onUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
leftDown = false;
else if (e.keyCode == Keyboard.RIGHT)
rightDown = false;
if (e.keyCode == Keyboard.UP)
upDown = false;
else if (e.keyCode == Keyboard.DOWN)
downDown = false;
}
public function onDown(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
leftDown = true;
else if (e.keyCode == Keyboard.RIGHT)
rightDown = true;
if (e.keyCode == Keyboard.UP)
upDown = true;
else if (e.keyCode == Keyboard.DOWN)
downDown = true;
}
public function addProjToScreen (projectile:Projectile) : void
{
addChild(projectile);
}
private function Run(e:Event):void
{
acceleration = 0; //resets acceleration back to 0 to limit speed
if (leftDown)
{
angle -= 5;
}
else if (rightDown)
{
angle += 5;
}
if (upDown)
{
acceleration += 3;
}
else if (downDown)
{
acceleration -= 3;
}
triSpeedX += acceleration * Math.cos(angle * Math.PI / 180);
triSpeedY += acceleration * Math.sin(angle * Math.PI / 180);
tri1.x += triSpeedX;
tri1.y += triSpeedY;
//borders
if (tri1.x < 0)
{
triSpeedX *= -.5;
tri1.x = 0 ;
}
if (tri1.x > 800 )
{
tri1.x = 800;
triSpeedX *= -.5;
}
if (tri1.y < 0)
{
triSpeedY *= -.5;
tri1.y = 0 ;
}
if (tri1.y > 600)
{
triSpeedY *= -.5;
tri1.y = 600;
}
//friction
triSpeedX *= 0.95
triSpeedY *= 0.95
rect1.x = tri1.x;
rect1.y = tri1.y;
var xCurDist:Number = curX - rect1.x;
var yCurDist:Number = curY - rect1.y;
turretAngle = Math.atan(yCurDist / xCurDist) * 180 / Math.PI ;
if (xCurDist < 0 )
{
turretAngle += 180;
}
if (xCurDist > 0 && yCurDist < 0 )
{
turretAngle += 360;
}
rect1.rotation= turretAngle + 90; // + 90 to account for the sprite originally pointing up, which is 270 degrees ccw
tri1.rotation = angle + 90;
for (var i:int = 0 ; i < projCount ; i ++)
{
projectileArr [i].move();
}
}
}
and the Projectile class:
public class Projectile extends MovieClip
{
private var projectile : Sprite = new Sprite();
private var speed: int = 10;
private var angle :Number;
private var xIncr: Number;
private var yIncr: Number;
public function Projectile(x:Number, y:Number, angle:Number)
{
this.x = x;
this.y = y;
this.angle = angle;
projectile.graphics.beginFill (0xFF0000);
projectile.graphics.drawCircle (x, y, 4);
projectile.graphics.endFill() ;
xIncr = speed * Math.cos (angle); // angle needs to be converted to radians
yIncr = speed * Math.sin (angle);
}
public function move () :void
{
trace (this.x + " " + this.y);
this.x += xIncr;
this.y += yIncr;
}
}
I just don't know what I'm missing... I'm calling addChild to all of my newly created objects, what else is there to do?
You are not adding the sprite projectile to the displaylist of Projectile in your constructor.
addChild(projectile);
Also you are doubling up on x and y co-ordinates in your projectile class. Rectify this by changing projectile.graphics.drawCircle (x, y, 4); to projectile.graphics.drawCircle (0, 0, 4);

Flash - using multiple event handlers?

so I'm working on a game which uses multiple .as files - and I'm trying to program the game however it keeps kicking back the following error when it reaches line 21 in theGame.as - the error is...
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at theGame()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\theGame.as:21]
at main/changeState()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\main.as:23]
at mainMenu/brnP_Button()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\mainMenu.as:40]
Cannot display source code at this location.
I'm using the following .as files.
main.as
//main.as
package
{
import flash.display.*;
import flash.system.fscommand;
public class main extends MovieClip
{
public function main()
{
changeState(null, "menu");
}
public function changeState (currentState, nextState)
{
if (currentState != null)
{
removeChild(currentState);
}
switch(nextState)
{
case "menu": var mm:mainMenu = new mainMenu(changeState);
addChild(mm);
break;
case "game": var g:theGame = new theGame(changeState);
addChild(g);
break;
case "exit": fscommand("quit");
break;
}
}
}
}
mainMenu.as
`
//mainMenu.as
package
{
import flash.display.*;
import flash.events.*;
public class mainMenu extends MovieClip
{
var theCallBackFunction:Function;
private var ballX:Number = 10; // Declaring a variable known as ballX
private var ballY:Number = 0; // Declaring a variable knwon as ballY
private const GRAVITY:Number = 2; // Declaring a const variable known as gravity
public const ROTATION:Number = 1;
public const BOUNCE:Number = 0.9;
var gameBall:Ball = new Ball();
public function mainMenu(callBack)
{
addEventListener(Event.ENTER_FRAME, menuFrameHandler);
addChild(gameBall);
var btnPlay:mmPlay = new mmPlay();
btnPlay.addEventListener(MouseEvent.MOUSE_DOWN, brnP_Button);
btnPlay.x = width/2;
btnPlay.y = height/2 - btnPlay.height/2;
addChild(btnPlay);
var btnExit:mmExit = new mmExit();
btnExit.addEventListener(MouseEvent.MOUSE_DOWN, brnE_Button);
btnExit.x = width/2;
btnExit.y = height/2 - btnExit.height/2;
btnExit.y += btnExit.height + 4;
addChild(btnExit);
theCallBackFunction = callBack;
}
public function brnP_Button(e:MouseEvent)
{
removeEventListener(Event.ENTER_FRAME, menuFrameHandler);
theCallBackFunction(this, "game");
return;
}
public function brnE_Button(e:MouseEvent)
{
theCallBackFunction(this, "exit");
return;
}
private function menuFrameHandler (e:Event):void
{
// Gravitate the Ball
ballY += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
gameBall.x += ballX;
gameBall.y += ballY;
gameBall.rotation += ROTATION * ballX;
checkBoundaryCollision();
}
private function checkBoundaryCollision():void
{
var left:Number;
var right:Number;
var bottom:Number;
left = gameBall.x - (gameBall.width / 2);
right = gameBall.x + (gameBall.width / 2);
bottom = gameBall.y;
if (left < 0 && ballX < 0)
{
gameBall.x = (gameBall.width / 2)
ballX *= -1;
}
else if (right > stage.stageWidth && ballX > 0)
{
gameBall.x = stage.stageWidth - (gameBall.width / 2)
ballX *= -1;
}
else if (bottom > stage.stageHeight && ballY > 0)
{
gameBall.y = stage.stageHeight - (gameBall.height/2)
ballY *= -BOUNCE;
}
}
}
}
theGame.as
//theGame.as
package
{
import flash.display.MovieClip
import flash.text.TextField
import flash.events.Event
import flash.events.MouseEvent
public class theGame extends MovieClip
{
public const GRAVITY:Number = 2; // Declaring a const variable known as gravity
public const BOUNCE:Number = 0.8;
public const HIT:Number = 15;
public const ROTATION:Number = 1;
public var gameBall:Ball;
private var ballX:Number; // Declaring a variable known as ballX
private var ballY:Number; // Declaring a variable knwon as ballY
public function theGame(callBack): void
{
addChild(gameBall);
ballX = Math.random(); // Initalising ballX
ballY = Math.random(); // Initalising ballY
gameBall.buttonMode = true;
addEventListener(Event.ENTER_FRAME, gameFrameHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
private function gameFrameHandler (e:Event):void
{
// Gravitate the Ball
ballY += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
gameBall.x += ballX;
gameBall.y += ballY;
gameBall.rotation += ROTATION * ballX;
// Check Stage Boundaries For Collisions
checkBoundaryCollision();
}
private function mouseDownHandler (e:MouseEvent):void
{
// Hit the ball if it has been clicked
if (e.target == gameBall)
{
hit(e.target.mouseX, e.target.mouseY);
}
}
private function checkBoundaryCollision():void
{
var left:Number;
var right:Number;
var bottom:Number;
var top:Number;
left = gameBall.x - (gameBall.width / 2);
right = gameBall.x + (gameBall.width / 2);
bottom = gameBall.y + (gameBall.height / 2);
top = gameBall.y - (gameBall.height / 2);
if (left < 0 && ballX < 0)
{
gameBall.x = (gameBall.width / 2)
ballX *= -1;
}
else if (right > stage.stageWidth && ballX > 0)
{
gameBall.x = stage.stageWidth - (gameBall.width / 2)
ballX *= -1;
}
if (top < 42.70 && ballY < 0)
{
gameBall.y = 42.70 + (gameBall.height / 2)
ballY *= -1;
}
else if (bottom > stage.stageHeight && ballY >= 0)
{
gameBall.y = stage.stageHeight - (gameBall.height/2)
ballY *= -BOUNCE;
ballX *= BOUNCE;
}
}
private function hit(hitX:Number, hitY:Number):void
{
// Adjust vertical velocity
if (ballY > 0)
{
ballY *= -BOUNCE / 2;
}
ballY -= HIT;
//adjust horizontal veloity
if (ballX * hitX > 0)
{
ballX *= -BOUNCE;
}
ballX -= (hitX / gameBall.width * HIT);
}
}
}
How would I go about fixing this?
You don't have an instance of gameBall inside your class theGame.
Try adding
gameBall = new Ball();
before
addChild(gameBall);

Making Subclass Objects Non-Null

I'm currently having some trouble with referencing objects that turn out null on export. Basically I want the Document Class to run the code of another class that is the class of a MovieClip without having Error 1009 popping up everywhere in my output panel.
Here's the subclass I'm trying to run:
package
{
import flash.display.*;
import flash.events.*;
import Document;
import RestartButton;
public class McMain extends MovieClip
{
public var document:Document;
public var leftKeyDown:Boolean = false;
public var rightKeyDown:Boolean = false;
public var upKeyDown:Boolean = false;
public var downKeyDown:Boolean = false;
public var onGround:Boolean = true;
public var xSpeed:Number = 0;
public var ySpeed:Number = 0;
public var mainSpeed:Number = 3.75;
public var frictionPower:Number = 0.9;
public var jumpPower:Number = 13;
public var gravityPower:Number = 0.5;
public var terminalVelocity:Number = 75;
public function McMain()
{
this.addEventListener(Event.ADDED_TO_STAGE, initMcMain);
// constructor code
}
public function initMcMain(event:Event)
{
addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
addEventListener(Event.ENTER_FRAME, hitTest);
addEventListener(Event.ENTER_FRAME, Main);
}
public function Main(event:Event):void
{
this.moveCharacter();
this.dynamicMovement();
}
public function checkKeysDown(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
this.leftKeyDown = true;
}
if (event.keyCode == 38)
{
this.upKeyDown = true;
}
if (event.keyCode == 39)
{
this.rightKeyDown = true;
}
if (event.keyCode == 40)
{
this.downKeyDown = true;
}
}
public function checkKeysUp(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
this.leftKeyDown = false;
}
if (event.keyCode == 38)
{
this.upKeyDown = false;
}
if (event.keyCode == 39)
{
this.rightKeyDown = false;
}
if (event.keyCode == 40)
{
this.downKeyDown = false;
}
}
public function moveCharacter():void
{
if (this.leftKeyDown)
{
this.xSpeed -= this.mainSpeed;
if (this.onGround)
{
this.scaleX = -1;
}
}
if (this.rightKeyDown)
{
this.xSpeed += this.mainSpeed;
if (this.onGround)
{
this.scaleX = 1;
}
}
if (this.leftKeyDown && this.onGround || this.rightKeyDown && this.onGround)
{
this.gotoAndStop(2);
}
if (this.currentFrame == 2)
{
if (! this.leftKeyDown && ! this.rightKeyDown)
{
this.gotoAndStop(3);
}
}
if (this.currentFrame == 3)
{
if (this.skidAnimation.currentFrame == this.skidAnimation.totalFrames)
{
this.gotoAndStop(1);
}
}
if (this.upKeyDown)
{
this.ySpeed -= this.jumpPower;
}
if (this.upKeyDown && this.leftKeyDown)
{
this.ySpeed -= 0;
this.xSpeed -= 10;
}
if (this.upKeyDown && this.rightKeyDown)
{
this.ySpeed -= 0;
this.xSpeed += 10;
}
if (this.xSpeed > 3 && ! onGround || this.xSpeed < -3 && ! onGround)
{
if (this.currentFrame == 2)
{
this.gotoAndStop(5);
}
}
if (this.ySpeed < -0.5 && ! onGround)
{
this.gotoAndStop(4);
}
else if (this.ySpeed > 0.5 && ! onGround)
{
this.gotoAndStop(5);
}
if (this.currentFrame == 5 && onGround)
{
this.gotoAndStop(1);
}
//if (! leftKeyDown && ! rightKeyDown && ! upKeyDown)
//{
//mcMain.gotoAndStop(1);
//}
}
public function dynamicMovement():void
{
if (onGround)
{
this.x += this.xSpeed;
this.xSpeed *= this.frictionPower;
}
else
{
this.x += this.xSpeed;
this.xSpeed *= (this.frictionPower + 0.09);
}
if (this.xSpeed > 7)
{
this.xSpeed = 7;
}
if (this.xSpeed < -7)
{
this.xSpeed = -7;
}
this.y += this.ySpeed;
this.ySpeed += this.gravityPower;
if (this.ySpeed > this.terminalVelocity)
{
this.ySpeed = this.terminalVelocity;
}
}
public function hitTest(event:Event)
{
//spawnArea.visible = false;
this.mcMainHitArea.visible = false;
this.document.levelChange.wallCollision.visible = false;
//^^^^^^^^^^^^^^^^^^^^^^^^^^
//Error 1009 appearing here!
this.document.levelChange.deathArea.visible = false;
this.document.levelChange.goalArea.goalHitArea.visible = false;
while (document.levelChange.wallCollision.hitTestPoint(this.x, this.y, true))
{
this.y = this.y - 0.5;
this.ySpeed = 0;
}
while (document.levelChange.wallCollision.hitTestPoint(this.x, this.y - 24, true))
{
this.y = this.y + 0.5;
this.ySpeed = 0;
}
while (document.levelChange.wallCollision.hitTestPoint(this.x - 12, this.y - 11, true))
{
this.x = this.x + 0.5;
this.xSpeed = 0;
if (! onGround)
{
this.leftKeyDown = false;
}
}
while (document.levelChange.wallCollision.hitTestPoint(this.x + 12, this.y - 11, true))
{
this.x = this.x - 0.5;
this.xSpeed = 0;
if (! onGround)
{
this.rightKeyDown = false;
}
}
if (document.levelChange.wallCollision.hitTestPoint(this.x - 16, this.y - 11, true))
{
if (this.upKeyDown)
{
this.ySpeed -= 10;
this.xSpeed += 50;
}
}
if (document.levelChange.wallCollision.hitTestPoint(this.x + 16, this.y - 11, true))
{
if (this.upKeyDown)
{
this.ySpeed -= 10;
this.xSpeed -= 50;
}
}
if (document.levelChange.wallCollision.hitTestPoint(this.x, this.y, true))
{
if (this.upKeyDown)
{
this.upKeyDown = false;
this.onGround = false;
}
}
if (! document.levelChange.wallCollision.hitTestPoint(this.x, this.y + 1, true))
{
if (! document.levelChange.wallCollision.hitTestPoint(this.x, this.y + 1.5, true))
{
this.upKeyDown = false;
}
if (! document.levelChange.wallCollision.hitTestPoint(this.x, this.y + 5, true))
{
//upKeyDown = false;
onGround = false;
}
}
if (document.levelChange.wallCollision.hitTestPoint(this.x, this.y + 1, true))
{
this.ySpeed = 0;
if (document.levelChange.wallCollision.hitTestPoint(this.x, this.y + 5, true))
{
onGround = true;
}
}
if (document.levelChange.deathArea.hitTestPoint(this.x, this.y + 1, true))
{
this.x = this.x;
this.y = this.y;
}
if (this.hitTestObject(document.levelChange.goalArea.goalHitArea))
{
if (stage.contains(document.level_1))
{
this.removeChild(document.level_1);
//stage.removeEventListener(Event.ENTER_FRAME,hitTest);
}
if (stage.contains(document.spawnArea))
{
this.x = this.x;
this.y = this.y;
}
addChild(document.level_2);
document.level_2.x = -1425;
document.level_2.y = -2550;
}
}
}
}
Document Class:
package
{
import flash.events.*;
import flash.display.*;
import flash.geom.Point;
import McMain;
import RestartButton;
import Level_2;
public class Document extends MovieClip
{
public var levelNumber:int = 1;
public var levelChange:Object;
public var levelArray:Array = new Array();
public var collisionArray:Array = new Array();
public var deathAreaArray:Array = new Array();
public var goalAreaArray:Array = new Array();
public var goalHitAreaArray:Array = new Array();
public var mcMain:McMain;
public var restartButton:RestartButton;
public var level_2:Level_2;
public function Document()
{
addEventListener(Event.ADDED_TO_STAGE, init);
mcMain = new McMain();
mcMain.document = this;
restartButton = new RestartButton();
restartButton.document = this;
level_2 = new Level_2();
// constructor code
}
public function init(event:Event)
{
this.levelChange = this.level_1;
}
public function levelHandler(event:Event)
{
this.levelChange = this["level_" + levelNumber];
if (level_2.stage)
{
levelNumber = 2;
//trace(levelChange);
}
for (var i:int = numChildren - 1; i >= 0; i--)
{
var collisionChild:DisplayObject = getChildAt(i);
if (collisionChild.name == "wallCollision")
{
collisionArray.push(collisionChild);
}
var deathAreaChild:DisplayObject = getChildAt(i);
if (deathAreaChild.name == "deathArea")
{
deathAreaArray.push(deathAreaChild);
}
var goalAreaChild:DisplayObject = getChildAt(i);
if (goalAreaChild.name == "goalArea")
{
goalAreaArray.push(goalAreaChild);
}
}
for (var i_2:int = numChildren - 2; i >= 0; i--)
{
var goalHitAreaChild:DisplayObject = getChildAt(i_2);
if (goalHitAreaChild.name == "goalHitArea")
{
goalHitAreaArray.push(goalHitAreaChild);
}
}
}
public function vCamMovement(event:Event):void
{
/*for (var i:int = 0; i < this.numChildren - 1; i++)
{
this.getChildAt(i).x -= xSpeed;
//levelObjects.getChildAt(i).y -= ySpeed;
}*/
level_1.x += stage.stageWidth * 0.5 - mcMain.x;
level_1.y += stage.stageHeight * 0.5 - mcMain.y;
level_2.x += stage.stageWidth * 0.5 - mcMain.x;
level_2.y += stage.stageHeight * 0.5 - mcMain.y;
spawnArea.x += stage.stageWidth * 0.5 - mcMain.x;
spawnArea.y += stage.stageHeight * 0.5 - mcMain.y;
mcMain.x = stage.stageWidth * 0.5;
mcMain.y = stage.stageHeight * 0.5;
}
}
}
Edit: Fixed a small typo within the code, but the code is still not working.
Edit:
Here's the debugger output:
TypeError: Error #1009: Cannot access a property or method of a null object reference. at McMain/hitTest()[C:\Users\*\Desktop\*\Flash\*\McMain.as:186] *= XXXXXXXXXXXX
Two things. 1st, I cannot see anywhere that you initialize level_1 object. Two, you should move this code out of your constructor object and into your init method.
mcMain = new McMain();
mcMain.document = this;
restartButton = new RestartButton();
restartButton.document = this;
The reason is simple. You're just creating mcMain, then setting its .document property to "this." Within mcMain, you're referencing mcMain.document.levelChange, but you do not define document.levelChange until later, in your init method. I'm not entirely convinced that this is absolutely your issue, but you really should be do doing error checking when you're accessing dynamic properties on a dynamic class. Try doing things like
if(document != null && document.levelChange != null)
before you attempt to explicitly reference those properties/objects as you are with your hitTest.