Trying to get AS3 to detect collision but get Error 1009 (Null Object) - actionscript-3

I've just only began learning AS3 as I have to create a simple game for an assignment, I have two objects named obj_laser and obj_enemy1 but when I run the collision code I created, it keeps coming up with the error 1009. Here is some of the code and I know its messy.
stage.addEventListener(Event.ENTER_FRAME, runGame);
function runGame(event: Event): void {
//Fire Laser
LASERALARM++;
if (LASERALARM >= 10) {
var laser: obj_laser = new obj_laser
var laser2: obj_laser = new obj_laser
var flare: obj_flare = new obj_flare
var flare2: obj_flare = new obj_flare
laser.x = obj_spaceship.x + 12
laser.y = obj_spaceship.y
laser2.x = obj_spaceship.x - 12
laser2.y = obj_spaceship.y
addChild(laser);
addChild(laser2);
flare.x = obj_spaceship.x + 12
flare.y = obj_spaceship.y
flare2.x = obj_spaceship.x - 12
flare2.y = obj_spaceship.y
addChild(flare);
addChild(flare2);
LASERALARM = 0;
//Move Laser
laser.addEventListener(Event.ENTER_FRAME, moveLaser);
function moveLaser(event: Event): void {
laser.y -= 5;
laser2.y -= 5;
}
}
//Spawn Enemies
ENEMYALARM++
if (ENEMYALARM >= (randomRange(100, 400))) {
var enemy1: obj_enemy1 = new obj_enemy1
enemy1.x = (randomRange(15, 165));
enemy1.y = -10;
addChild(enemy1);
ENEMYALARM = 0;
//Move Enemy
enemy1.addEventListener(Event.ENTER_FRAME, moveEnemy);
function moveEnemy(event: Event): void {
enemy1.y += 2;
}
if (laser.hitTestObject(enemy1)) {
parent.removeChild(laser);
parent.removeChild(enemy1);
}
}

Essentially you are trying to do something with a variable that doesn't have a value.
Clicking on the error should take you to where it breaks down in the code. Further to that, start tracing out your variables at different points of the code to try and nail it down.

Related

RemoveChild on Button Click

I'm currently trying to remove a graphic 'lose_mc' that i added to the scene using addChild.
When trying to use removeChild when the user clicks the next level_btn, this error appears:
TypeError: Error #2007: Parameter listener must be non-null.
at flash.events::EventDispatcher/removeEventListener()
at Function/<anonymous>()
Any one has any ideas of why this isn't working? This is my code at the minute.
**
import flash.net.URLRequest;
import flash.display.MovieClip;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.Event;
import flash.display.Loader;
stop();
//stage.removeEventListener(Event.ENTER_FRAME, nextButtonClick);
var hitObstacle:Boolean=false;
var points=2; //The points will be set at 2
points_txt.text=points.toString(); //Health will be displayed in points_txt box
var lose_mc = new lose();
var win_mc = new win();
//crowhit_mc.visible=false;
var loader:Loader = new Loader()
addChild(loader);
//var url:URLRequest = new URLRequest("test.swf");
//var lose_mc = new lose();
//var win_mc = new win();
//var hitObstacle:Boolean=false;
var leafArray:Array = new Array(leaf01,leaf02,leaf03);
var leafsOnstage:Array = new Array();
var leafsCollected:int = 0;
var leafsLost:int = 0;
for (var i:int = 0; i<20; i++) {
var pickLeaf = leafArray[int(Math.random() * leafArray.length)];
var leaf:MovieClip = new pickLeaf();
addChild(leaf);
leaf.x = Math.random() * stage.stageWidth-leaf.width;// fruit.width is subtracted from the random x position to elimate the slight possibility that a clip will be placed offstage on the right.
leaf.y = Math.random() * -500;
leaf.speed = Math.random() * 15 + 5;
leafsOnstage.push(leaf);
}
basket_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragBasket);
stage.addEventListener(MouseEvent.MOUSE_UP, dragStop);
function dragBasket(e:Event):void {
basket_mc.startDrag();
}
function dragStop(e:Event):void {
basket_mc.stopDrag();
}
stage.addEventListener(Event.ENTER_FRAME, catchLeaf);
function catchLeaf(e:Event):void {
for (var i:int = leafsOnstage.length-1; i > -1; i--) {
var currentLeaf:MovieClip = leafsOnstage[i];
currentLeaf.y += currentLeaf.speed;
if (currentLeaf.y > stage.stageHeight - currentLeaf.height) {
currentLeaf.y = 0 - currentLeaf.height;
leafsLost++;
field2_txt.text = "Total Leaves Lost: " + leafsLost;
}
if (currentLeaf.hitTestObject(basket_mc)) {
leafsCollected++;
removeChild(currentLeaf);
leafsOnstage.splice(i,1);
field1_txt.text = "Total Leaves Collected: " + leafsCollected;
if (leafsCollected >= 20) {
basket_mc.gotoAndStop(20);
} else if (leafsCollected > 15) {
basket_mc.gotoAndStop(15);
} else if (leafsCollected>10) {
basket_mc.gotoAndStop(10);
} else if (leafsCollected>5) {
basket_mc.gotoAndStop(5);
}
}
}
if (leafsOnstage.length <= 0) {
field1_txt.text = "You Win! You have collected enough leaves for the day.";
nextlevel_btn.addEventListener(Event.ENTER_FRAME, fl_FadeSymbolINwin);
nextlevel_btn.alpha = 0;
function fl_FadeSymbolINwin(event:Event)
{
nextlevel_btn.alpha += 0.01;
if(nextlevel_btn.alpha >= 1)
{
nextlevel_btn.removeEventListener(Event.ENTER_FRAME, fl_FadeSymbolIn);
}
}
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchLeaf);
var win_mc = new win();
win_mc.x = 215.70;
win_mc.y = 163.25;
win_mc.w = 100;
win_mc.h = 145;
addChild(win_mc);
removeChild(crow_mc);
}
if (leafsLost >= 20) {
field1_txt.text = "Sorry you lose. You have lost too many leaves!";
restart_btn.addEventListener(Event.ENTER_FRAME, fl_FadeSymbolIn);
restart_btn.alpha = 0;
function fl_FadeSymbolIn(event:Event)
{
restart_btn.alpha += 0.01;
if(restart_btn.alpha >= 1)
{
restart_btn.removeEventListener(Event.ENTER_FRAME, fl_FadeSymbolIn);
}
}
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchLeaf);
for (var j:int = leafsOnstage.length-1; j > -1; j--) {
currentLeaf = leafsOnstage[j];
removeChild(currentLeaf);
leafsOnstage.splice(j,1);
lose_mc.x = 215.70;
lose_mc.y = 163.25;
lose_mc.w = 100;
lose_mc.h = 145;
addChild(lose_mc); //this is the movieclip in my library im adding it to the screen
}
}
}
//nextlevel_btn.addEventListener(MouseEvent.CLICK, nextButtonClick);
/*restart_btn.addEventListener(MouseEvent.CLICK, buttonClick)
function buttonClick(e:MouseEvent):void
{
try{
loader_mc.unloadAndStop();
} catch(e:Error) {
}
var urlRequest : URLRequest = new URLRequest("test.swf");
loader_mc.load(urlRequest);
removeChild(win_mc);
}
//function nextButtonClick(e:MouseEvent):void{
//removeChild(win_mc);
//loader.unloadAndStop();
//var request:URLRequest = new URLRequest("test.swf");
//loader.load(request);
crow_mc.addEventListener(MouseEvent.CLICK,rotateCrow);
function rotateCrow(e:MouseEvent):void {
crow_mc.rotation +=10;
var myTween:Tween = new Tween(crow_mc, "alpha", Strong.easeOut, 1,10,25, true);
}
*/
var crow_mcSpeedX:int = -6;
var crow_mcSpeedY:int = 2;
stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(evt:Event) {
crow_mc.x += crow_mcSpeedX;
crow_mc.y += crow_mcSpeedY;
//because the ball's position is measured by where its CENTER is...
//...we need add or subtract half of its width or height to see if that SIDE is hitting a wall
//first check the left and right boundaries
if(crow_mc.x <= crow_mc.width/2){ //check if the x position of the left side of the ball is less than or equal to the left side of the screen, which would be 0
crow_mc.x = crow_mc.width/2; //then set the ball's x position to that point, in case it already moved off the screen
crow_mcSpeedX *= -1; //and multiply the ball's x speed by -1, which will make it move right instead of left
} else if(crow_mc.x >= stage.stageWidth-crow_mc.width/2){ //check to see the right side of the ball is touching the right boundary, which would be 550
crow_mc.x = stage.stageWidth-crow_mc.width/2; //reposition it, just in case
crow_mcSpeedX *= -1; //multiply the x speed by -1 (now moving left, not right)
}
//now we do the same with the top and bottom of the screen
if(crow_mc.y <= crow_mc.height/2){ //if the y position of the top of the ball is less than or equal to the top of the screen
crow_mc.y = crow_mc.height/2; //like we did before, set it to that y position...
crow_mcSpeedY *= -1; //...and reverse its y speed so that it is now going down instead of up
} else if(crow_mc.y >= stage.stageHeight-crow_mc.height/2){ //if the bottom of the ball is lower than the bottom of the screen
crow_mc.y = stage.stageHeight-crow_mc.height/2; //reposition it
crow_mcSpeedY *= -1; //and reverse its y speed so that it is moving up now
}
//}
//points--; //Health is decreased by 1 each time a trap_mc is clicked
//points_txt.text=points.toString();
//lose_mc.visible=true;
if (basket_mc.hitTestObject(crow_mc)) { //If the player_mc hits the sharkfin_mc
if (hitObstacle==false){ //Only subtract health if hitObstacle is false
trace("Hit Object")
//crow_mc.visible=false; //crow_mc becomes invisible
//removeChild(leaf);
//leafsOnstage.visable = false;
//lose_mc.x = 215.70;
//lose_mc.y = 163.25;
//lose_mc.w = 100;
//addChild(lose_mc);
points--; //Points are decreased by 1 each time crow_mc is hit - hittestobject()
points_txt.text=points.toString();
}
hitObstacle=true;
}
}
restart_btn.addEventListener(MouseEvent.CLICK, backButtonClick);
function backButtonClick(e:MouseEvent):void{
removeChild(lose_mc);
loader.unloadAndStop();
var request:URLRequest = new URLRequest("test.swf");
loader.load(request);
}
nextlevel_btn.addEventListener(MouseEvent.CLICK, nextButtonClick);
function nextButtonClick(e:MouseEvent):void{
loader.unloadAndStop();
var request:URLRequest = new URLRequest("snowflake.swf");
loader.load(request);
}
**
This is the area of code that is causing the problem..
**
nextlevel_btn.addEventListener(MouseEvent.CLICK, nextButtonClick);
function nextButtonClick(e:MouseEvent):void{
removeChild(win_mc);
loader.unloadAndStop();
var request:URLRequest = new URLRequest("snowflake.swf");
loader.load(request);
}
**
That is not the area causing the problem because Flash clearly says:
TypeError: Error #2007: Parameter listener must be non-null.
at flash.events::EventDispatcher/removeEventListener()
at Function/<anonymous>()
As we can see, the error is happening in removeEventListener.
removeEventListener takes two parameters: event and listener.
What we can also see, Flash says: parameter listener must be non-null.
That means that parameter listener passed to removeEventListener is null.
The part of your code that may cause the error is the following:
if (leafsOnstage.length <= 0) {
field1_txt.text = "You Win! You have collected enough leaves for the day.";
nextlevel_btn.addEventListener(Event.ENTER_FRAME, fl_FadeSymbolINwin);
nextlevel_btn.alpha = 0;
function fl_FadeSymbolINwin(event:Event)
{
nextlevel_btn.alpha += 0.01;
if(nextlevel_btn.alpha >= 1)
{
nextlevel_btn.removeEventListener(Event.ENTER_FRAME, fl_FadeSymbolIn);
}
}
First, you are adding listener fl_FadeSymbolINwin, but you remove a different listener fl_FadeSymbolIn. Second, for some reason you are declaring a function inside an if block. What you need to do is to get your code formatting right and check where and how you do removeEventListener's with what parameters. Trace them if needed.
Also I suggest using TweenLite (or even TweenNano) for fade effects. You won't have to mess with all these EventListeners. Your code for fading button would look as simple as this:
TweenNano.to(nextlevel_btn, 0.5, {alpha:1});

hitTestObject issue // remove stage Error #2025

hey :S I`m trying to make 2 things so far but neither work :(
The 1st is to make an Row of 5 Ships that position them selves from the top to left.Then add an Event to make them move down.
But every time i try to make a new Row of 5 new ships ... they position themselves after the last ship from the previous Row.I did think of a way to fix that by waiting the 1st Row of ships to go beyond the stage and then remove them from the stage and splice from the Array but ... when I increase the speed of spawning (when i have 2 rows with 5 ships on the stage or more)that does't work.
And the second error I think is from that fact .... that I have 2 rows at the same time on the stage.
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at MainClass/doShips()
at MainClass/everyFrame()
I dont know what exactly to paste from the code so i had to push everything in the MainClass of the FLA.fail :D but i did it neatly! so if anyone helped me he would track the code easily
so its a simple FLA.fail with 4 MC and in those 4 MC there is no code
a Bullet
a Ship with colour Yellow
a Ship2 with colour Green so i can see the randomising
and a Player with the class Turret
so the MainClass of the FLA is :
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class MainClass extends MovieClip {
protected var mouseSpeed:Number = 20;
protected var _thePlayer:Turret = new Turret();
protected var shipCount:Number;
protected var shipCount2:Number;
protected var shipArray:Array = new Array();
protected var counter:int = 0;
//variables for bullets
private var shootCooldown:Number = 0; //speed of the fire
private var firing:Boolean = false;//bullets triger
private var numToShoot:int = 1; //bullets
const MAX_COOLDOWN = 10; //bullets timer
protected var _bulletsArray:Array = new Array();
public function MainClass() {
_thePlayer.x = stage.stageWidth/2
_thePlayer.y = stage.stageHeight - _thePlayer.height/2
addChild(_thePlayer)
addEventListener(Event.ENTER_FRAME, everyFrame)
stage.addEventListener(MouseEvent.MOUSE_DOWN, startFire);
stage.addEventListener(MouseEvent.MOUSE_UP, stopFire);
}
private function startFire(ev:MouseEvent) {
firing = true;
}
private function stopFire(ev:MouseEvent) {
firing = false;
}
//every frame do this
protected function everyFrame(ev:Event):void{
//Moving The Turret
moveTheTurret();
//increase the counter every frame
counter++;
if(counter % 70 == 0){
//position the ships on the stage
positionShips();
}
//handle the ships when they are added on the stage
doShips();
//when to fire
updateFire();
//handle the bullets
doBullets();
}
//Moving The Turret
protected function moveTheTurret() {
if (mouseX > _thePlayer.x +15) {
_thePlayer.x += mouseSpeed;
} else if (mouseX < _thePlayer.x - 15) {
_thePlayer.x -= mouseSpeed;
} else {
_thePlayer.x = mouseX;
}
}
//createShips and position them
protected function positionShips() {
shipCount = 3;
shipCount2 = 2;
var gap = 10;
for (var i:int = 0; i < shipCount; i++) {
var s = new Ship();
shipArray.push(s);
}
for (var j:int = 0; j < shipCount2; j++) {
s = new Ship2();
shipArray.push(s);
}
var array:Array=new Array();
while (shipArray.length>0) {
var index:uint = Math.floor(Math.random() * shipArray.length);
array.push(shipArray[index]);
shipArray.splice(index,1);
}
shipArray = array;
//shipsArray has been randomized
for (var k:int = shipArray.length - 1; k >= 0; k--) {
addChild(shipArray[k]);
shipArray[k].x = shipArray[k].width/2 + (shipArray[k].width * k) + (gap*k);
}
}
//move the ships
protected function doShips() {
for (var i:int = shipArray.length - 1; i >= 0; i--) {
shipArray[i].y +=3 //make the Ships fall down
for (var bcount= _bulletsArray.length-1; bcount >= 0; bcount--) {
//if the bullet is touching the ship
if (shipArray[i].hitTestObject(_bulletsArray[bcount])) {
//if we get here it means there`s is a collision
removeChild(_bulletsArray[bcount]);
_bulletsArray.splice(bcount,1);
removeChild(shipArray[i]);
_bulletsArray.splice(i,1);
}
}
//if it gets over 380 remove from stage and splice from the array
if(shipArray[i].y > 380){ // stage.stageHeight)
removeChild(shipArray[i]);
shipArray.splice(i,1);
}
}
}
//when to fire
public function updateFire() {
//if we are currently holding the mouse down
if(firing == true){
fire();
}
//reduce the cooldown by 1 every frame
shootCooldown--;
}
//Shoot bullets
private function fire() {
if (shootCooldown <= 0) {
//reset the cooldown
shootCooldown = MAX_COOLDOWN
for (var i=0; i<numToShoot; i++){
//spown a bullet
var b = new Bullet();
//set the rotation of the bullet
b.rotation = -90
b.x = _thePlayer.x;
b.y = _thePlayer.y;
//add the bullet to the list/Array of _bulletsArray
_bulletsArray.push(b);
//add the bullet to the perent object;
addChild(b);
}
}
}
//handling the bullets
protected function doBullets(){
//make a for loop to iterate all the _bulletsArray on the screen
for (var bcount:int = _bulletsArray.length-1; bcount>=0; bcount--) {
//make the bullets move Up
_bulletsArray[bcount].y -=20;
//if the bullet is beyond the screen remove from the stage and the Array
if(_bulletsArray[bcount].y < 0){
removeChild(_bulletsArray[bcount])
_bulletsArray.splice(bcount,1);
}
}
}
}
}
I dont know how to fix neither of the 2 problems.Would be very thankful for any help!!!
Thanks in advance.

HitTest Function with two parameters not initializing

Hey guys so Basically what I'm trying to do is when my player collides with all 5 of the points MovieClips in an array and the Goal Movie Clip i want a text to appear saying "Perfect. But i cant quite accomplish this. I set up the function and it seems like it would but i think what might be wrong is the hitTest with all the Movie clips in the array.
Here is how i set it up:
This is in my loop Function:
private function gameLoop(e:Event):void
{
perfectTextFunction();
}
This is the function:
private function perfectTextFunction():void
{
if (player.hitTestObject(mcGoal_1 && points))
{
trace("perfect Text");
mcPerfect = new perfectText();
mcPerfect.x = (stage.stageWidth / 2);
mcPerfect.y = (stage.stageHeight/ 2);
stage.addChild(mcPerfect);
}
}
The Trace doesn't pick anything up.
Here is how the points are added to the stage if needed:
public function addPointsToStage():void
{
for (var i = 0; i < nPoints; i++)
{
trace(aPointsArray.length);
points = new mcGainPoints();
stage.addChild(points);
points.x = startPoint.x + (xSpacing * i);
points.y = startPoint.y - (ySpacing * i);
aPointsArray.push(points);
}
}
Please any help would be appreciated! THank you!
VESPER here is how I made the NESTED LOOP:
//If all points are hit then Perfect Hit Text
if (player.hitTestObject(mcGoal_1 || mcGoal_2))
{
var weHitAll:Boolean = true;
for (var s in aPointsArray)
{
weHitAll = weHitAll && player.hitTestObject(aPointsArray[s]);
if (!weHitAll)
break;
}
if (weHitAll)
{
trace("perfect Hit");
mcPerfect = new perfectText();
mcPerfect.x = (stage.stageWidth / 2);
mcPerfect.y = (stage.stageHeight/ 2) - 80;
stage.addChild(mcPerfect);
nScore += 25;
updateHighScore();
}
}
var weHitAll:Boolean=true;
for (var s in aPointsArray) {
weHitAll = weHitAll&&player.hitTestObject(aPointsArray[s]);
if (!weHitAll) break; // missed one, drop cycle
}
if (weHitAll) {
trace('Perfect hit!');
... // etc
}
Function hitTestObject accepts only a single object as parameter, in order to check against an array you need to iterate through it, checking against one object at a time (here it's in aPointsArray[s]).

AS3 not recognising MovieClips - 1046: Type was not found or was not a compile-time constant: MP_00

So Im new to AS3, trying to make a simple videogame for smartphones.
And it was all going smooth until I hit this problem.
I was using and manipulating objects from timeline without a problem and than all the sudden whatever I try I get the 1046.
Here is some code that gets an error:
mp = new MP_00();
And at the top I have this:
import flash.display.MovieClip;
var mp:Movieclip;
And at the end this:
function mapMove(){
mp.y = mp.y - playerSpeed;
}
Im searching for a solution all the time, but nobody seems to have the same problem.
I do have AS linkage set to MP_00 and witch ever object I try to put in, it dosent work.
While objects put in on the same way before, they work.
For example I have this
var player:MovieClip;
player = new Player();
with AS Linkage set to Player, and that works.
This is all done in Flash Professional cs6
EDIT 1
full code
Keep in mind that a lot of stuff is placeholder or just not finished code.
On this code Im getting the error twice for the same object
Scene 1 1046: Type was not found or was not a compile-time constant:
MP_00.
Scene 1, Layer 'Actions', Frame 1, Line 165 1046: Type was not
found or was not a compile-time constant: MP_00.
Thats the errors.
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.engine.SpaceJustifier;
import flashx.textLayout.operations.MoveChildrenOperation;
/*----------------------------Main VARs-----------------------------*/
var STATE_START:String="STATE_START";
var STATE_START_PLAYER:String="STATE_START_PLAYER";
var STATE_PLAY:String="STATE_PLAY";
var STATE_END:String="STATE_END";
var gameState:String;
var player:MovieClip;
var playerSpeed:Number;
var map:Array;
var bullets:Array;
//holds civil vehicles
var civil:Array;
//holds enemy vehicles
var enemy:Array;
var explosions:Array;
var BBullet:MovieClip;
//maps
var mp:MovieClip;
/*
var MP_01:MovieClip;
var MP_02:MovieClip;
var MP_03:MovieClip;
*/
//sets the bullet type and properties
var BType = "BBasic";
var BProp:Array;
//bullet preperties by type
var BBasic:Array = new Array(1, 1, 100, 50, 0, new BBasicA());
/**
ARRAY SETTING
0 = bullet position (middle , back, sides etc...)
1-middle front
2-left side front
3-right side front
4-left and right side middle
5-back
7-left and right side wheels
1 = bullet direction
1-forward
2-back
3-sides
2 = fire speed (in millisecounds so 1000 = 1sec)
3 = speed of movement
4 = damage 10-100
5 = name of the firing animation in library
6 = name of launch animation in library
7 = name of impact animation in library
**/
var level:Number;
//BCivil speed and randomness
var BCSpeed:Number = 3;
var BCRand:Number = 120;
/*------------------------------Setup-------------------------------*/
introScreen.visible = false;
loadingScreen.visible = false;
gameScreen.visible = false;
endScreen.visible = false;
//map visibility
//MpRSimple.visible = false;
/*---------------------------Intro screen--------------------------*/
/*-----------------------------mainScreen---------------------------*/
mainScreen.play_btn.addEventListener(MouseEvent.CLICK, clickAway);
function clickAway(event:MouseEvent):void
{
gameStart();
}
function gameStart():void
{
//Move main screen from stage
mainScreen.visible = false;
//Begin loading the game
loadingScreen.visible = true;
gameState = STATE_START;
trace (gameState);
addEventListener(Event.ENTER_FRAME, gameLoop);
}
/*----------------------------gameLoop-----------------------------*/
function gameLoop(e:Event):void
{
switch(gameState)
{
case STATE_START:
startGame();
break;
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END:
endGame();
break;
}
}
/*-_________________________-Game STATES-_________________________-*/
/*---------------------------STATE_START---------------------------*/
function startGame():void
{
level = 1; //setting level for enemies
//Graphics
//player icon
player = new Player();
//add bullet holder
bullets = new Array();
//basicCivil icon
civil = new Array();
//basicEnemy icon
enemy = new Array();
//holds explosions
explosions = new Array();
//map
//mp = new MP_00();
//var mp:MP_00 = new MP_00();
//Load map parts
//End startGame
gameState = STATE_START_PLAYER;
trace(gameState);
}
/*------------------------STATE_START_PLAYER-----------------------*/
function startPlayer():void
{
//start the player
//set possition of player
player.y = stage.stageHeight - player.height;
addChild(player);
addEventListener(Event.ENTER_FRAME, movePlayer);
//changing screens
gameScreen.visible = true;
//start game
gameState = STATE_PLAY;
trace(gameState);
}
//player controll
function movePlayer(e:Event):void
{
//gameScreen.visible = true;
//mouse\touch recognition
player.x = stage.mouseX;
player.y = stage.mouseY;
//player does not move out of the stage
if (player.x < 0)
{
player.x = 0;
}
else if (player.x > (stage.stageWidth - player.width))
{
player.x = stage.stageWidth + player.width;
}
}
//setting bullet type
if (BType == "BBasic")
{
BProp = BBasic;
/*case BMissile;
BProp = BMissile;
break; */
}
//creating bullets
//gameScreen.fire_btn.addEventListener(MouseEvent.CLICK, fireHandler());
/*
function fireHandler():void
{
var bulletTimer:Timer = new Timer (500);
bulletTimer.addEventListener(TimerEvent.TIMER, timerListener);
bulletTimer.start();
trace("nja");
}
function timerListener(e:TimerEvent):void
{
//need and if statement to determine the bullet speed and travel depended on type of bullet
var tempBullet:MovieClip = /*BProp[5] new BBasicA();
//shoots bullets in the middle
tempBullet.x = player.x +(player.width/2);
tempBullet.y = player.y;
//shooting speed
tempBullet.speed = 10;
bullets.push(tempBullet);
addChild(tempBullet);
//bullets movement forward
for(var i=bullets.length-1; i>=0; i--)
{
tempBullet = bullets[i];
tempBullet.y -= tempBullet.speed;
}
}
*/
/*----------------------------STATE_PLAY---------------------------*/
function playGame():void
{
//gameplay
//speedUp();
mapMove();
//fire();
makeBCivil();
makeBEnemy();
moveBCivil();
moveBEnemy();
vhDrops();
testCollision();
testForEnd();
removeExEplosions();
}
function mapMove(){
mp.y = mp.y - playerSpeed;
}
/*
function speedUp():void
{
var f:Number;
for (f<10; f++;)
{
var playerSpeed = playerSpeed + 1;
f = 0;
//mapMove();
MpRSimple = new MP_RS();
MpRSimple.y = MpRSimple.y - playerSpeed;
trace ("speed reset");
}
trace (f);
}
*/
function makeBCivil():void
{
//random chance
var chance:Number = Math.floor(Math.random()*BCRand);
if (chance <= 1 + level)
{
var tempBCivil:MovieClip;
//generate enemies
tempBCivil = new BCivil();
tempBCivil.speed = BCSpeed;
tempBCivil.x = Math.round(Math.random()*800);
addChild(tempBCivil);
civil.push(tempBCivil);
}
}
function moveBCivil():void
{
//move enemies
var tempBCivil:MovieClip;
for(var i:int = civil.length-1; i>=0; i--)
{
tempBCivil = civil[i];
tempBCivil.y += tempBCivil.speed
}
//testion colision with the player and screen out
if (tempBCivil.y > stage.stageHeight /* || tempBCivil.hitTestObject(player) */)
{
trace("ds hit");
//makeExplosion (player.x, player.y);
removeCivil(i);
//gameState = STATE_END;
}
}
//Test bullet colision
function testCollision():void
{
var tempBCivil:MovieClip;
var tempBEnemy:MovieClip;
var tempBullet:MovieClip;
//civil/bullet colision
civils:for(var i:int=civil.length-1; i>=0; i--)
{
tempBCivil = civil[i];
for (var j:int=bullets.length-1; j>=0; j--)
{
tempBullet = bullets[j];
if (tempBCivil.hitTestObject(tempBullet))
{
trace("laser hit the civil");
makeExplosion (tempBCivil.x, tempBCivil.y);
removeCivil(i);
removeBullet(j);
break civils;
}
}
}
//enemy/bullet colision
enemy:for(var k:int=enemy.length-1; k>=0; k--)
{
tempBEnemy = enemy[k];
for (var l:int=bullets.length-1; l>=0; l--)
{
tempBullet = bullets[l];
if (tempBEnemy.hitTestObject(tempBullet))
{
trace("bullet hit the Enemy");
makeExplosion (tempBEnemy.x, tempBEnemy.y);
removeEnemy(k);
removeBullet(l);
break enemy;
}
}
}
}
function makeExplosion(ex:Number, ey:Number):void
{
var tempExplosion:MovieClip;
tempExplosion = new boom();
tempExplosion.x = ex;
tempExplosion.y = ey;
addChild(tempExplosion)
explosions.push(tempExplosion);
}
function makeBEnemy():void
{
//random chance
var chance:Number = Math.floor(Math.random()*BCRand);
if (chance <= 1 + level)
{
var tempBEnemy:MovieClip;
//generate enemies
tempBEnemy = new BEnemy();
tempBEnemy.speed = BCSpeed;
tempBEnemy.x = Math.round(Math.random()*800);
addChild(tempBEnemy);
enemy.push(tempBEnemy);
}
}
function moveBEnemy():void
{
//move enemies
var tempBEnemy:MovieClip;
for(var i:int = enemy.length-1; i>=0; i--)
{
tempBEnemy = enemy[i];
tempBEnemy.y += tempBEnemy.speed
}
//testion colision with the player and screen out
if (tempBEnemy.y > stage.stageHeight /* || tempBCivil.hitTestObject(player) */)
{
trace("enemy");
//makeExplosion (player.x, player.y);
removeEnemy(i);
//gameState = STATE_END;
}
}
function vhDrops():void
{}
function testForEnd():void
{
//check damage
//end game
//gameState = STATE_END;
trace(gameState);
}
/*--------------------REMOVING BS FROM STAGE-----------------------*/
//removing civils
function removeCivil(idx:int):void
{
if(idx >= 0)
{
removeChild(civil[idx]);
civil.splice(idx, 1);
}
}
//removing enemies
function removeEnemy(idx:int):void
{
if(idx >= 0)
{
removeChild(enemy[idx]);
enemy.splice(idx, 1);
}
}
//removing civils
function removeBullet(idx:int):void
{
if(idx >= 0)
{
removeChild(bullets[idx]);
bullets.splice(idx, 1);
}
}
//removing expired explosions
function removeExEplosions():void
{
var tempExplosion:MovieClip;
for(var i=explosions.length-1; i>=0; i--)
{
tempExplosion = explosions[i];
if (tempExplosion.currentFrame >= tempExplosion.totalFrames)
{
removeExplosion(i);
}
}
}
//removing civils
function removeExplosion(idx:int):void
{
if(idx >= 0)
{
removeChild(explosions[idx]);
explosions.splice(idx, 1);
}
}
/*--------------------------STATE_END------------------------------*/
function endGame():void
{
}
/*gameScreen*/
/*endScreen*/
And Im sure theres some other bad code here but that doesent matter now.
Export for AS and AS Linkage is set:
http://i.stack.imgur.com/UvMAt.png
EDIT: removed the 2nd var declaration, still get the same error.
It would be great if you give more code and explanations, but here what I found about 1046 :
"One reason you will get this error is if you have an object on the stage with the same name as an object in your library."
Look at : http://curtismorley.com/2007/06/20/flash-cs3-flex-2-as3-error-1046/
Did you search any explanation on the Web for code 1046 ? Have you checked this one ?
I see that you have two var mp declaration. Try to remove the first one, var mp:MovieClip;. If it doesn't work, check your Flash Library carefully, be sure that MP_00 is a name available. If it's a MovieClip, check that it is exported for ActionScript. If it's an instance name, check that it's not used twice.
EDIT.
My suggestion is :
1- Change all references of mp to mp1. Maybe there is a conflict with an instance "...an object on the stage with the same name as an object in your library."
2- var mp1:MP_00; instead of var mp:MovieClip; in the declaration section.
3- Put the mp1 = new MP_00(); back in the startGame() function
4- Be sure that your new mp1 variable is everywhere you need and you have no more ref. to mp variable.
If... it's still doesn't work. I suggest : Change the name of your MovieClip linkage, like TestA, or whatever. Yes I know, a doubt on everything, but there is no magic, testing everything will show the problem for sure.
EDIT.
For mapMove() function...
First : be sure the speedUp() function is available, not in comments, and call it in your playGame() function. Your playerSpeed variable must have a value, so change : var playerSpeed = playerSpeed + 1; for playerSpeed = playerSpeed + 1;. Do not use var declaration twice for the same variable. (See var playerSpeed:Number; in header file.)
Beside... you have to know if the MP_00 clip on stage is YOUR mp1 clip. (I assumed you published all the code you have.)
Case A : MP_00 is on stage when you start your Clip.
If you actually see your MP_00 on screen, that mean you don't have to do mp1 = new MP_00(); and addchild(mp1);. It's already done for you (dragging a clip from library and giving a name instance, is the same as doing new and addchild).
Find the instance name (or give one). You should get your instance name and move your object (here the instance name is mp1):
mp1.y = mp1.y - playerSpeed;
Case B : MP_00 is NOT on stage when you start your Clip.
Do :
1- your declaration : var mp1:MP_00;
2- allocation memory : mp1 = new MP_00();
3- add to the display list : addchild(mp1);
4- "Shake it bb" : mp1.y = mp1.y - playerSpeed; or mp1.y -= playerSpeed;
I don't know what is your knowledge level exactly, so I tried to put everything. Sorry if it's too much.

"Error#2025 The supplied DisplayObject must be a child of the caller." upon trying to removeChild();

I'm creating a simple iPhone game (but the class I'm in is requiring me to use Flash...), and I'm having a major issue as I'm trying to remove objects from the game.
The game is somewhat of a dynamic time-wasting bubblewrap game where there are infinite "refreshes" of the stage. Once the user pops all the bubbles, more randomly generate. (When the array is empty, call the setup() again.)
For now, I have one of each five different colored bubble graphics pulled from the library by code and placed on the stage randomly. However, I don't like the overlap, so I've given each bubble a small square hitspace so when they're placed randomly and overlap significantly they pop themselves. For some reason when I'm trying to remove the bubbles it gives me
Error#2025 The supplied DisplayObject must be a child of the caller.
I've tried adding stage to addChild and removeChild, but I get the same error.
import flash.events.*;
import flash.display.*;
var bubbles:Array = new Array();
var b:BlueBubble = new BlueBubble();
var b2:GreenBubble = new GreenBubble();
var b3:PinkBubble = new PinkBubble();
var b4:PurpleBubble = new PurpleBubble();
var b5:YellowBubble = new YellowBubble();
// values to be tweaked later
var bNum:uint = 1;
var maxSize:uint = 100;
var minSize:uint = 1;
var range:uint = maxSize - minSize;
var tooBig:uint = 100;
function init():void {
setup();
stage.addEventListener(Event.ENTER_FRAME, onEveryFrame);
}
function setup():void {
for (var i:uint=0; i<bNum; i++) {
// blue
b.width = Math.ceil(Math.random() * range) + minSize;
b.height = b.width;
b.x = Math.random()*(stage.stageWidth - b.width);
b.y = Math.random()*(stage.stageHeight - b.height);
bubbles.push(b);
stage.addChild(b);
// green
b2.width = Math.ceil(Math.random() * range) + minSize;
b2.height = b2.width;
b2.x = Math.random()*(stage.stageWidth - b2.width);
b2.y = Math.random()*(stage.stageHeight - b2.height);
bubbles.push(b2);
stage.addChild(b2);
// pink
b3.width = Math.ceil(Math.random() * range) + minSize;
b3.height = b3.width;
b3.x = Math.random()*(stage.stageWidth - b3.width);
b3.y = Math.random()*(stage.stageHeight - b3.height);
bubbles.push(b3);
stage.addChild(b3);
// purple
b4.width = Math.ceil(Math.random() * range) + minSize;
b4.height = b4.width;
b4.x = Math.random()*(stage.stageWidth - b4.width);
b4.y = Math.random()*(stage.stageHeight - b4.height);
bubbles.push(b4);
stage.addChild(b4);
// yellow
b5.width = Math.ceil(Math.random() * range) + minSize;
b5.height = b5.width;
b5.x = Math.random()*(stage.stageWidth - b5.width);
b5.y = Math.random()*(stage.stageHeight - b5.height);
bubbles.push(b5);
stage.addChild(b5);
//add event listeners for bubbles later
}
}
function onEveryFrame(e:Event) {
for (var i:uint=0; i<bubbles.length; i++) {
bubbles[i].width++;
bubbles[i].height++;
if (bubbles[i].height >= tooBig && bubbles[i].width >= tooBig) {
bubbles[i].height = tooBig;
bubbles[i].width = tooBig;
}
// Blue hit testing
if (b2.hitGreen.hitTestObject(b.hitBlue)) {
removeChild(b);
}
if (b3.hitPink.hitTestObject(b.hitBlue)) {
removeChild(b);
}
if (b4.hitPurple.hitTestObject(b.hitBlue)) {
removeChild(b);
}
if (b5.hitYellow.hitTestObject(b.hitBlue)) {
removeChild(b);
}
// Other hit testing...
}
}
init();
You are adding b, b2, b3, etc to the stage, but removing them from whatever object is executing this code. Try changing
stage.addChild(b);
to
addChild(b);
Additionally, it is a good idea to check that an object is a child before removing it. Try changing
if (...)
removeChild(b);
to
if (contains(b) && ...)
removeChild(b);
The best way to solve this is:
mc.parent.removeChild(mc);
Basically, the removeChild function needs to be called from whatever display object that your soon to be removed object is in.