Error 1136 : incorrect number of arguments. Expected 0 - actionscript-3

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

Hi I don't understand why you are getting this error, but this can help you,
try the follow code instead of Point();
var checkPoints:Array=new Array({x:85,y:140},
{x:85,y:320},
{x:325,y:320},
{x:325,y:200},
{x:265,y:200},
{x:265,y:80},
{x:505,y:80},
{x:505,y:380},
{x:630,y:380}
);

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

Remove timer event listener

so I need to remove a timer event. But the problem is, It's in another function so I can't access it.
Here's how my code goes:
-There is a Boss
-It generates bomb
-Bomb lasts for a couple of seconds before exploding (no error)
-Bomb can be removed by clicking. (generates error)
If the bomb was removed via clicking, there will be error because the time event wasn't remove. But like I said, I can't remove it because it's in another function. Help!
import flash.events.Event;
import flash.display.MovieClip;
var boss:MovieClip = new darklord();
this.addChild(boss);
boss.x = stage.stageWidth / 2;
boss.y = stage.stageHeight / 2;
var lives:int = 3;
var maxHP:int = 2000;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;
var bombcontainer:Array = [];
var timecontainer:Array = [];
function updateHealthBar():void
{
percentHP = currentHP / maxHP;
healthBar.barColor.scaleX = percentHP;
}
boss.addEventListener(MouseEvent.CLICK, TapBoss);
boss.addEventListener(Event.ENTER_FRAME, MoveBoss);
function TapBoss(e:MouseEvent):void
{
currentHP -= 10;
if (currentHP <= 0)
{
currentHP = 0;
trace("You win!");
}
updateHealthBar();
}
var timerBoss:Timer = new Timer(1000,60);
timerBoss.addEventListener(TimerEvent.TIMER, bosstimerhandler);
timerBoss.start();
var secondsBoss:Number = 0;
function bosstimerhandler(event:TimerEvent)
{
//trace("Seconds elapsed: " + seconds);
//SpawnNote(null);
if (secondsBoss%5==0)
{
RandomCoord(null);
BossAttack(null);
}
secondsBoss++;
}
var HighH:int = stage.stageHeight;
var HighW:int = stage.stageWidth;
var LowH:int = 0;
var LowW:int = 0;
var destinationX:int;
var destinationY:int;
function RandomCoord(event:Event):void
{
destinationX=Math.floor(Math.random()*(1+HighW-LowW))+LowW;
destinationY=Math.floor(Math.random()*(1+HighH-LowH))+LowH;
if (destinationX <= 50)
{
destinationX += 50;
}
if (destinationY <= 50)
{
destinationY += 50;
}
if (destinationX + 50 >= stage.stageWidth)
{
destinationX -= 50;
}
if (destinationY + 50 >= stage.stageHeight)
{
destinationY -= 50;
}
trace("X is: ", destinationX);
trace("Y is: ", destinationY);
}
function MoveBoss(event:Event):void
{
if (boss.x < destinationX)
{
boss.x += 1;
}
else if (boss.x > destinationX)
{
boss.x -= 1;
}
if (boss.y < destinationY)
{
boss.y += 1;
}
else if (boss.y > destinationY)
{
boss.y -= 1;
}
}
function BossAttack(event:Event):void
{
var boom:MovieClip = new Bomb();
this.addChild(boom);
bombcontainer.push(boom);
boom.x = boss.x;
boom.y = boss.y;
BombCoord(null);
boom.addEventListener(Event.ENTER_FRAME, MoveBomb);
boom.addEventListener(MouseEvent.CLICK, TapBomb(boom));
BombTimer(boom);
}
function BombTimer(boom:MovieClip):void
{
var time:Timer = new Timer(1000,30);
timecontainer.push(time);
time.addEventListener(TimerEvent.TIMER, TimeHandler);
time.start();
var t:Number = 1;
function TimeHandler(event:TimerEvent):void
{
trace("Seconds elapsed: " + t);
t++;
if (t==12)
{
lives--;
trace("You lost a life!");
time.removeEventListener(TimerEvent.TIMER, TimeHandler);
RemoveBomb(boom, 0);
}
}
}
function RemoveBomb(boom:DisplayObject, bid:int):void
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
//boom.removeEventListener(MouseEvent.CLICK, TapBomb(boom));
bombcontainer.splice(bid, 1);
trace("Bomb # :" +bid+" is popped.");
this.removeChild(boom);
}
var BombX:int;
var BombY:int;
function BombCoord(event:Event):void
{
BombX=Math.floor(Math.random()*(1+HighW-LowW))+LowW;
BombY=Math.floor(Math.random()*(1+HighH-LowH))+LowH;
if (BombX <= 50)
{
BombX += 50;
}
if (BombY <= 50)
{
BombY += 50;
}
if (BombX + 50 >= stage.stageWidth)
{
BombX -= 50;
}
if (BombY + 50 >= stage.stageHeight)
{
BombY -= 50;
}
}
function MoveBomb(event:Event):void
{
var boom:DisplayObject = event.target as DisplayObject;
var fl_TimerInstance:Timer = new Timer(1000,6);
fl_TimerInstance.addEventListener(TimerEvent.TIMER, fl_TimerHandler);
fl_TimerInstance.start();
var fl_SecondsElapsed:Number = 1;
function fl_TimerHandler(event:TimerEvent):void
{
//trace("Seconds elapsed: " + fl_SecondsElapsed);
fl_SecondsElapsed++;
if (fl_SecondsElapsed==4)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
if (boom.x < BombX)
{
boom.x += 5;
//boom.x +=5;
}
else if (boom.x > BombX)
{
boom.x -= 5;
}//boom.x -=5;
if (boom.y < BombY)
{
boom.y += 5;
//boom.x +=5;
}
else if (boom.y > BombY)
{
boom.y -= 5;
}
if (boom.x == BombX)
{
if (boom.y == BombY)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
if (boom.y == BombY)
{
if (boom.x == BombX)
{
boom.removeEventListener(Event.ENTER_FRAME, MoveBomb);
}
}
}
function TapBomb(boom:MovieClip):Function
{
return function(e:MouseEvent):void {
var BombIndex:int = bombcontainer.indexOf(boom);
trace("You clicked the bomb at index " + BombIndex);
RemoveBomb(boom, BombIndex);
}
}
It's not that bad having a frame event listener on each bomb, unless perhaps you have hundreds of bombs at the same time.
You can solve the issue by making the Bomb a separate class that has its own handlers and timer. Something like this (not tested):
package {
import flash.display.*;
import flash.net.*;
import flash.utils.Timer;
public class Bomb extends MovieClip {
private var myTimer:Timer;
public function Bomb() {
myTimer = new Timer(1000,30);
myTimer.addEventListener(TimerEvent.TIMER, TimeHandler);
myTimer.start();
}
private function TimeHandler(event:TimerEvent):void {
// check the time
}
public function stopTicking():void {
this.myTimer.stop();
}
}
}
You can then create all the bombs you want and kill their timers by calling their method:
// create a bomb movieclip and add it to the displaylist
var myBomb = new Bomb();
bombContainer.addChild(myBomb);
// use the displaylist to keep track of nonexploded bombs
var someBomb = bombContainer.getChildAt(0);
// stop the timer on this bomb
someBomb.stopTicking();

TypeError: Error #1009 cant find the NULL object

I got this really annoying error
"TypeError: Error #1009: Cannot access a property or method of a null object reference.
at monke2_fla::MainTimeline/update2()"
I can't find the NULL var, any help would be great as the script works fine, apart from the #1009 error.
var randomX:Number = Math.random() * 800;
Banana_mc1.x = randomX;
Banana_mc1.y = 0;
var speed:Number = 10;
var speed2:Number = 5;
var speed3:Number = 2;
var speed4:Number = 6;
Banana_mc1.addEventListener(Event.ENTER_FRAME, moveDown);
var playerScore:int = 0;
var stopLoop = 0;
if (stopLoop == 1) { } else {
function moveDown(e:Event):void
{
Banana_mc1.y += speed;
Banana_mc2.y += speed2;
Banana_mc3.y += speed3;
Banana_mc4.y += speed3;
Banana_mc5.y += speed;
Banana_mc6.y += speed4;
Snake_mc1.y += speed2;
Bunch.y += speed3;
Snake_mc2.y += speed3;
}
}
// KEYS
stage.addEventListener (KeyboardEvent.KEY_DOWN, myFunction) ;
//Monkey.addEventListener(Event.ENTER_FRAME, update);
function myFunction (event: KeyboardEvent)
{
if(event.keyCode == Keyboard.LEFT)
Monkey.x -= 10;
if(event.keyCode == Keyboard.RIGHT)
Monkey.x += 10;
}
var hitAry:Array = [Banana_mc1,Banana_mc2,Banana_mc3,Banana_mc4,Banana_mc5,Banana_mc6];
var hitAry2:Array = [Snake_mc1,Snake_mc2];
stage.addEventListener(Event.ENTER_FRAME, update2);
function update2(e:Event):void
{
var hitAry:Array = [Banana_mc1,Banana_mc2,Banana_mc3,Banana_mc4,Banana_mc5,Banana_mc6];
var hitAry2:Array = [Snake_mc1,Snake_mc2];
for (var i:int=0; i < hitAry.length; i++) {
if (Monkey.hitTestObject(hitAry[i])) {
trace("HIT");
hitAry[i].parent.removeChild(hitAry[i]);
trace(hitAry[i]);
playerScore+=1;
playerScoreText.text = ("" + playerScore);
} else {
trace("MISS"); }
if (Floor.hitTestObject(hitAry[i])) {
trace("HIT The Floor");
hitAry[i].gotoAndPlay(35);
stopLoop = 1;
} else {
trace("MISS"); }
}
for (var b:int=0; b < hitAry2.length; b++) {
if (Monkey.hitTestObject(hitAry2[b])) {
Monkey.Head.gotoAndPlay(23);
trace("HIT");
hitAry2[b].parent.removeChild(hitAry2[b]);
playerScore-=1;
if (playerScore <= 0) { playerScore = 0; }
playerScoreText.text = ("" + playerScore);
} else {
trace("MISS"); }
}
if (Monkey.hitTestObject(allleft)) {
Monkey.Head.gotoAndPlay(23);
trace("BITE");
playerScore-=100;
if (playerScore <= 0) { playerScore = 0; }
playerScoreText.text = ("" + playerScore);
} else {
trace("NO BITE"); }
if (Monkey.hitTestObject(allright)) {
Monkey.Head.gotoAndPlay(23);
trace("BITE");
playerScore-=100;
if (playerScore <= 0) { playerScore = 0; }
playerScoreText.text = ("" + playerScore);
} else {
trace("NO BITE"); }
if (Monkey.hitTestObject(Bunch)) {
trace("HIT BUNCH");
Bunch.parent.removeChild(Bunch);
playerScore+=10;
playerScoreText.text = ("" + playerScore);
}
}
This is for an assignment that is over due and I am hitting a brick wall, Thanks in advance
Chelsea
Well, near the bottom of your code you say: Bunch.parent.removeChild(Bunch);
But you also have: Banana_mc1.addEventListener(Event.ENTER_FRAME, moveDown); which invokes a function that keeps referring to Bunch.
You could test that by NOT removing Bunch. If that fixes the null var problem then you'll have to decide how to proceed. Do you want the game to continue or end after Bunch goes away?
Then there's also this:
hitAry[i].parent.removeChild(hitAry[i]);
trace(hitAry[i]);
You're trying to trace it right after you remove it! That mightmake hitAry[i] null!

AS3 Generating differnet Enemies and bullets hitTest Problems

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

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.