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

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.

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

Added child stays invisible even though its container is visible

I have been struggling for a couple of days with an issue in Flash CS4. I am re-structuring an old game project into a Main class which handles the mainMenu, playGame, etc. functions. I have a ship added from the "game", which is added by Main.
The issue is "myShip" works as expected, except it's never visible. I've checked a lot of times, and both myShip and its containter (game) visible properties are always true. Alpha values are not the problem either, nor layers nor depth. Every other child I've added from "game" works just fine, but "myShip" refuses to be visible.
Any ideas as to why this could happen? I do not know how what to try next to solve the problem. Any help would be very appreciated. The code for the Main, Game and Ship class is below.
Thank you!
Code from the Main class:
public class Main extends Sprite {
public var mainMenuDisplay:MainMenuDisplay;
public var game:Game;
public var gameOverMenu:GameOverMenu;
public function Main() {
showMainMenu();
}
public function showMainMenu() {
mainMenuDisplay = new MainMenuDisplay(this);
gameOverMenu=remove_movie_clip(gameOverMenu);
addChild(mainMenuDisplay);
}
public function showGameOver() {
gameOverMenu = new GameOverMenu(this);
game=remove_movie_clip(game);
addChild(gameOverMenu);
}
public function playTheGame() {
game = new Game(this);
mainMenuDisplay = remove_movie_clip(mainMenuDisplay);
gameOverMenu=remove_movie_clip(gameOverMenu);
stage.addChild(game);
}
private function remove_movie_clip(clip:*) {
if (clip) {
removeChild(clip);
}
return null;
}
}
Code from the Game class:
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import com.coreyoneil.collision.CollisionList;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import com.greensock.*;
import flash.display.Sprite;
import flash.display.SpreadMethod;
import flash.display.GradientType;
import flash.geom.Matrix;
import com.sounds.music.Music_mainMusic;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.DisplayObject;
public class Game extends MovieClip {
var mainClass:Main;
//Main menu
//var mainMenuDisplay:MainMenuDisplay = new MainMenuDisplay();
//static var inMenu:Boolean = true;
//
//Ship variables
static var myShip:Ship = new Ship();
var myDirectionBar:Direction_bar = new Direction_bar();
//
//Enemy variables
static var enemyShipTimer_1:Timer;
//
//PowerUp variables
static var powerUpTimer:Timer;
static var nuking:Boolean;
//
//Wall generation variables
static var wall_mov_speed:Number;
var randomize:Number = 1;
var wallArray:Array = new Array();
var index:int = 0;
//
//Wall collision variables (powered by CDK by Corey O'Neil)
var myWallCollisionList:CollisionList; // = new CollisionList(myShip);
var wall_collisions:Array = new Array();
//
//Score variables
static var score:Number;
static var scoreText:TextField = new TextField();
var scoreFormat = new TextFormat("LCD5x8H", 20, 0x0066FF, true);
var distance_score_counter:int;
//
//Health variables
static var healthMeter_1:HealthMeter = new HealthMeter();
//
//Game modes
//var levelSelectDisplay:LevelSelectDisplay = new LevelSelectDisplay();
//**NOTE: These are extremely important, because they are the functions, which in reality are attributes, that allow us to call,
//from an Event Listener, a function in which we have a parameter to pass. This way we call these variables instead of the
//function we are interested in, these will call it for us.
//var functionLevelSelect_1:Function = selectedLevel(1);
//var functionLevelSelect_2:Function = selectedLevel(2);
//var functionLevelSelect_3:Function = selectedLevel(3);
//var functionLevelSelect_4:Function = selectedLevel(4);
//var functionLevelSelect_5:Function = selectedLevel(5);
//The level composition (that's the numbers of the frame in the MC of the Walls, each number is a type. The last one stores all of them.
//var level_1_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_2_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_3_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_4_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var storyModeLevelCompositions:Array = new Array(level_1_composition, level_2_composition, level_3_composition, level_4_composition);
//
var levelPlaying:int = 0;
var wallPieceCount:int = 0;
//
//Pause variables
var pauseScreen:PauseScreen = new PauseScreen();
//This variables states whether we are in pause or not
static var isPause:Boolean = false;
//This other tells us if we can pause at the moment or not
static var isPauseable:Boolean = false;
//
//Game Over, new Game and Game menu variables
//static var gameOverMenu:GameOverMenu = new GameOverMenu();
static var inGameStopping:Boolean = false;
//
//Transition screen variables
var darkening:Boolean;
//NOTE: We do it this way because, when putting an Enter Frame event listener onto the function funcTransition,
//which has a pass variable, the variable changed all the time to true, giving us problems.
//Background graphics variables
var color1:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var color2:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var colors:Object = {left:color1, right:color2};
var newColor1:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var newColor2:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var newColors:Object = {left:newColor1, right:newColor2};
var mySprite:Sprite = new Sprite();
//
//Music variables
var myMainMusic:Music_mainMusic = new Music_mainMusic();
//
//Credits variables
//var myCredits:Credits = new Credits();
//var myVersion:VersionDisplay = new VersionDisplay();
//
//Other variables
//var initThingy:Boolean;
var initTransition:Boolean = true;
var allPurposeCounter:int = 0;
var myTransitionScreen:TransitionScreen = new TransitionScreen();
//
//New necessary variables
//
public function Game(passedClass:Main) {
mainClass = passedClass;
if (stage) {
init(null);
}else{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
public function init(e:Event) {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
this.parent.addChild(this);
//Necessary initial booting:
mySprite.x = 0;
mySprite.y = 0;
stage.addChildAt(mySprite, 1);
drawGradient();
animateBackground();
//////////////////////////////////////////////////////
/*mainMenuDisplay.x = 400 - mainMenuDisplay.width/2;
mainMenuDisplay.y = 240 - mainMenuDisplay.height/2;
stage.addChild(mainMenuDisplay);*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*levelSelectDisplay.x = 400 - levelSelectDisplay.width/2;
levelSelectDisplay.y = 240 - levelSelectDisplay.height/2;
levelSelectDisplay.visible = false;
stage.addChild(levelSelectDisplay);*/
//////////////////////////////////////////////////////
//Transitions
myTransitionScreen.visible = false;
stage.addChild(myTransitionScreen);
//
//////////////////////////////////////////////////////
//myCredits.x = 20;
//myCredits.y = 438;
//stage.addChild(myCredits);
//myVersion.x = 710;
//myVersion.y = 438;
//stage.addChild(myVersion);
//////////////////////////////////////////////////////
//myMainMusic.play(0,99999);
initGame(null);
//mainMenuIdleState();
//
}
//////////////////////////////////////////////////////
/*function mainMenuIdleState(){
stage.addChild(mainMenuDisplay);
stage.addChild(levelSelectDisplay);
inMenu = true;
mainMenuDisplay.visible = true;
mainMenuDisplay.mainMenuPlayStoryButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, level_select);
mainMenuDisplay.mainMenuPlayEndlessButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, endless_mode_selected);
}*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*function endless_mode_selected(e:Event){
levelPlaying = 0;
initGame(null);
}*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*function level_select(e:Event){
mainMenuDisplay.visible = false;
levelSelectDisplay.visible = true;
levelSelectDisplay.levelSelectButton1_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_1);
levelSelectDisplay.levelSelectButton2_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_2);
levelSelectDisplay.levelSelectButton3_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_3);
levelSelectDisplay.levelSelectButton4_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_4);
levelSelectDisplay.levelSelectButtonBack_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_5);
}
function selectedLevel(level:int):Function {
switch (level){
case 1:
return function(e:MouseEvent):void {
//trace("1 clicked");
levelPlaying = 1;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 2:
return function(e:MouseEvent):void {
//trace("2 clicked");
levelPlaying = 2;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 3:
return function(e:MouseEvent):void {
//trace("3 clicked");
levelPlaying = 3;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 4:
return function(e:MouseEvent):void {
//trace("4 clicked");
levelPlaying = 4;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
default:
return function(e:MouseEvent):void {
//trace("back clicked");
levelPlaying = 0;
levelSelectDisplay.visible = false;
mainMenuDisplay.visible = true;
levelSelectDisplay.levelSelectButton1_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_1);
levelSelectDisplay.levelSelectButton2_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_2);
levelSelectDisplay.levelSelectButton3_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_3);
levelSelectDisplay.levelSelectButton4_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_4);
levelSelectDisplay.levelSelectButtonBack_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_5);
}
break;
}
}*/
//////////////////////////////////////////////////////
function initGame(e:Event):void{
//This has so many redundancies, when everything is done, START CLEANING THIS!
//////////////////////////////////////////////////////
//Main menu
//mainMenuDisplay.visible = false;
//inMenu = false; THIS GOES AT THE END TO PREVENT PROBLEMS
//directNewGame tells us if we come from the newGame function (and thus we do not go through the mainMenuIdleState
//function and this instances have not been placed on stage) or not. If we come from the main menu, we DO need to
//remove them.
//
trace(myShip);
//Ship
myShip.x = -10; //Before there were numbers to implement stage.stageWidth/2;
myShip.y = 200; //Before there were numbers to implement stage.stageHeight/2;
myShip.visible = true;
//mainClass.addChild(myShip);
this.addChild(myShip);
//We make sure the ship doesn't enter to stage with 0 health
//(problems of working with only one instance of ship due to the static var references)
Ship.health = 100;
//Check "NOTE" below
myShip.alpha = 0.35;
myShip.visible = true;
//
trace(myShip.visible);
//Direction bar
myDirectionBar.x = stage.stageWidth/2;
myDirectionBar.y = stage.stageHeight/2;
this.addChild(myDirectionBar);
//
//Timers (enemies)
enemyShipTimer_1 = new Timer(1000)
enemyShipTimer_1.addEventListener(TimerEvent.TIMER, spawn_enemies);
enemyShipTimer_1.start();
//
//Timer (powerUps)
powerUpTimer = new Timer(10000);
powerUpTimer.addEventListener(TimerEvent.TIMER, spawn_powerUp);
powerUpTimer.start();
//
//PowerUps (other)
nuking = false;
//
myWallCollisionList = new CollisionList(myShip);
//Initial movement speed of the walls
wall_mov_speed = 8;
//Calling to the generating/adequating wallArray function
adequateArrayOfWalls(true);
wallArray[0].gotoAndStop(1);
wallArray[1].gotoAndStop(1);
myWallCollisionList.addItem(wallArray[0].theActualWall);
myWallCollisionList.addItem(wallArray[1].theActualWall);
//Collision managements
wall_collisions = 0 as Array;
//NOTE: Here we limit the alpha value to consider for collision just to make sure the game doesn't start with you killed, and that you are "invincible"
//for some time
myWallCollisionList.alphaThreshold = 0.95;
//
//Adding score format and text
scoreText.defaultTextFormat = scoreFormat;
scoreText.x = 700;
scoreText.y = 10;
score = 0;
scoreText.text = String(score);
stage.addChild(scoreText);
distance_score_counter = 0;
scoreText.visible = true;
//
//Adding health meter
healthMeter_1 = new HealthMeter();
healthMeter_1.x = 10;
healthMeter_1.y = 10;
stage.addChild(healthMeter_1);
//
//Adding the Pause screen & other pause variables
pauseScreen.x = 400 - pauseScreen.width/2;
pauseScreen.y = 240 - pauseScreen.height/2;
pauseScreen.visible = false;
stage.addChild(pauseScreen);
isPauseable = true;
//Adding a key managing event (for pausing, menu, etc.)
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyManaging);
//
/*//Adding a Game Over Menu
gameOverMenu = new GameOverMenu();
gameOverMenu.x = 400 - gameOverMenu.width/2;
gameOverMenu.y = 240 - gameOverMenu.height/2;
gameOverMenu.visible = false;
stage.addChild(gameOverMenu);
gameOverMenu.playAgainButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, newGame);
gameOverMenu.backToMenuButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, backToTheMenu);
//*/
//Shield
//
//Event listeners
addEventListener(Event.ENTER_FRAME, update_game);
//
//////////////////////////////////////////////////////
/*//Credits
myCredits.visible = false;
myVersion.visible = false;
//
initThingy = true;
inMenu = false;*/
//////////////////////////////////////////////////////
}
function update_game(e:Event){
myShip.visible = true;
//Look the adequate array function for more info. We are just moving the two pieces of the array on stage
wallArray[(index - 1)].x -= wall_mov_speed;
wallArray[index].x -= wall_mov_speed;
if(wallArray[index].x < 0){
spawn_wall_piece();
}
//
if(index == 5){
//We call this function for cleaning
adequateArrayOfWalls(false);
}
if(wall_mov_speed < 20){
wall_mov_speed += 0.003;
}
wall_collisions = myWallCollisionList.checkCollisions();
if(wall_collisions.length > 0){
trace("hit!");
if(myShip.visible == true){
//We only kill the ship if it's visible, if not, it means it is already dead
Ship.receiveDamage(Ship.max_health);
}
wall_collisions = 0 as Array;
}
if(distance_score_counter >= 10){
distance_score_counter = 0;
updateScore(1);
}
distance_score_counter++;
//NOTE2: We use this nuke variable in order not to make the "nuke()" function static, type in which we couldn't handle the stage property
//And we also make this variable false here so as to eliminate not only a single enemy but all on stage
Enemy1.enemies_1Nuked = false;
if(nuking == true){
Enemy1.enemies_1Nuked = true;
nuking = false;
}
//We put these all the time at the front so we can see them and the walls don't overpass them
scoreText.parent.setChildIndex(scoreText, scoreText.parent.numChildren - 1);
healthMeter_1.parent.setChildIndex(healthMeter_1, healthMeter_1.parent.numChildren - 1);
pauseScreen.parent.setChildIndex(pauseScreen, pauseScreen.parent.numChildren -1);
//gameOverMenu.parent.setChildIndex(gameOverMenu, gameOverMenu.parent.numChildren - 1);
var n:uint = stage.numChildren;
for(var i=0; i < n; i++){
if(stage.getChildAt(i) is Enemy1){
var anEnemy1:Enemy1 = Enemy1(stage.getChildAt(i));
anEnemy1.parent.setChildIndex(anEnemy1, anEnemy1.parent.numChildren -1);
}
else if(stage.getChildAt(i) is PowerUp){
var aPowerUp:PowerUp = PowerUp(stage.getChildAt(i));
aPowerUp.parent.setChildIndex(aPowerUp, aPowerUp.parent.numChildren -1);
}
}
//Done like this due to the impossibility of calling a function inside an static one (in this case, gameOver)
if(inGameStopping == true){
funcEasing();
}
//Probably not necessary later
//////////////////////////////////////////////////////
/*if(initThingy == true){
stage.focus = stage;
initThingy = false;
}*/
//////////////////////////////////////////////////////
}
function spawn_enemies(e:Event){
var myEnemy1:Enemy1 = new Enemy1();
stage.addChild(myEnemy1);
}
function spawn_wall_piece(){
index++;
wallArray[index].x = (wallArray[index - 1].x + wallArray[index - 1].width);
wallArray[index].y = 0;
stage.addChild(wallArray[index]);
myWallCollisionList.addItem(wallArray[index].theActualWall);
myWallCollisionList.removeItem(wallArray[index - 2].theActualWall);
stage.removeChild(wallArray[index - 2]);
}
function adequateArrayOfWalls(init:Boolean):void{
//This only executes if we are initialitizing the array
if(init == true){
for(index = 0; index < 10; index++){
var aWall:Walls = new Walls();
//We check if we got special blocks next (e.g. "ramp caves"). Then we only allow a certain type of blocks to come.
//If no special block is detected, then we just randomize the next one, except for those that are not allowed to
//show up unless a previous special one appeared.
if(randomize == 9 || randomize == 15){
randomize = 15 + Math.floor(Math.random()*1 + 1);
}else{
randomize = Math.floor(Math.random()*14 + 1);
}
aWall.gotoAndStop(randomize);
//TheActualWall is the raw shape of the wall, where the ship collides, and it is what we push into collisionList,
//but not into the wallArray which includes the Walls (comprised by graphics and actual walls)
aWall.theActualWall.gotoAndStop(randomize);
wallArray.push(aWall);
}
wallArray[0].gotoAndStop(1);
wallArray[0].theActualWall.gotoAndStop(1);
stage.addChild(wallArray[0]);
wallArray[1].x = 800;
wallArray[1].y = 0;
stage.addChild(wallArray[1]);
//if not, then we are just cleaning it and rearranging it so it doesn't grow bigger and bigger
}else{
for(var a:Number = 0; a < index - 1; a++){
wallArray.splice(0,1);
}
for(a = index - 1; a < (10-2); a++){
var aWall2:Walls = new Walls();
if(randomize == 9 || randomize == 15){
randomize = 15 + Math.floor(Math.random()*1 + 1);
}else{
randomize = Math.floor(Math.random()*14 + 1);
}
aWall2.gotoAndStop(randomize);
aWall2.theActualWall.gotoAndStop(randomize);
wallArray.push(aWall2);
}
}
//Then, either way, we tell index to be 1 since the reference in the function is [index - 1] and [index], so it starts with [0] and [1]
index = 1;
}
static function updateScore(points:Number){
score += points;
scoreText.text = score.toString();
}
static function resetScore(){
score = 0;
scoreText.text = score.toString();
}
function spawn_powerUp(e:Event){
var pU:PowerUp = new PowerUp();
stage.addChild(pU);
}
static function gameOver(){
wall_mov_speed = 8;
//gameOverMenu.end_game_score_display.text = score.toString();
//gameOverMenu.visible = true;
scoreText.visible = false;
enemyShipTimer_1.stop();
powerUpTimer.stop();
inGameStopping = true; //In game stopping only influentiates in the easing speed effect
isPauseable = false;
}
function funcEasing(){
if(wall_mov_speed >= 0.1){
wall_mov_speed /= 1.07;
}else{
wall_mov_speed = 0;
removeEventListener(Event.ENTER_FRAME, update_game);
initTransition = true;
darkening = true; //See notes on variable declaration.
funcTransition(null);
}
}
function funcTransition(e:Event){
if(initTransition == true){
myTransitionScreen.init(darkening);
myTransitionScreen.parent.setChildIndex(myTransitionScreen, stage.numChildren - 1);
myTransitionScreen.parent.addEventListener(Event.ENTER_FRAME, funcTransition);
initTransition = false;
allPurposeCounter = 0;
}
if((darkening == true && myTransitionScreen.alpha == 1) || (darkening == false && myTransitionScreen.alpha == 0)){
trace("fsdfa");
allPurposeCounter++;
trace(allPurposeCounter);
if(allPurposeCounter >= 20){
myTransitionScreen.parent.removeEventListener(Event.ENTER_FRAME, funcTransition);
initTransition = true;
allPurposeCounter = 0;
if(darkening == true){ //This means if we are now with a black screen coming from the game, which is when we will end our game process
endGameProcess();
}
}
}
}
function endGameProcess(){
mainClass.showGameOver();
}
function newGame(e:Event){
darkening = true; //See notes on variable declaration.
initTransition = true;
funcTransition(null);
}
//Check To-Do List below
function funcPause(pMode:String){
if(pMode == "pausing"){
pauseScreen.visible = true;
removeEventListener(Event.ENTER_FRAME, update_game);
myShip.thePause("pausing");
//Check and stop the childs on stage (emitted by stage, so particles don't count)
var n:uint = stage.numChildren;
for(var i=0; i < n; i++){
if(stage.getChildAt(i) is Enemy1){
var anEnemy1:Enemy1 = Enemy1(stage.getChildAt(i));
anEnemy1.thePause("pausing");
}
else if(stage.getChildAt(i) is Trail){
var aTrailUnit:Trail = Trail(stage.getChildAt(i));
aTrailUnit.thePause("pausing");
}
else if(stage.getChildAt(i) is PowerUp){
var aPowerUp:PowerUp = PowerUp(stage.getChildAt(i));
aPowerUp.thePause("pausing");
}
}
enemyShipTimer_1.stop();
powerUpTimer.stop();
isPause = true;
isPauseable = false;
}else if(pMode == "unpausing"){
pauseScreen.visible = false;
addEventListener(Event.ENTER_FRAME, update_game);
myShip.thePause("unpausing");
//Check and re-run the childs on stage (emitted by stage, so particles don't count)
var m:uint = stage.numChildren;
for(var j=0; j < m; j++){
if(stage.getChildAt(j) is Enemy1){
var anotherEnemy1:Enemy1 = Enemy1(stage.getChildAt(j));
anotherEnemy1.thePause("unpausing");
}
else if(stage.getChildAt(j) is Trail){
var anotherTrailUnit:Trail = Trail(stage.getChildAt(j));
anotherTrailUnit.thePause("unpausing");
}
else if(stage.getChildAt(j) is PowerUp){
var anotherPowerUp:PowerUp = PowerUp(stage.getChildAt(j));
anotherPowerUp.thePause("unpausing");
}
}
enemyShipTimer_1.start();
powerUpTimer.start();
isPause = false;
isPauseable = true;
}
}
//Key pressing management
function keyManaging(e:KeyboardEvent){
var key:uint = e.keyCode;
trace("algo");
switch (key){
case Keyboard.P:
if(isPause == false && isPauseable == true){
funcPause("pausing");
}else if (isPause == true){
funcPause("unpausing");
}
break;
case Keyboard.M:
//go back to menu: still to complete
//Has to be only possible to do while in the pause menu
trace("going back to menu");
//
break;
}
}
//
//Background color management
function drawGradient():void {
var m:Matrix = new Matrix();
m.createGradientBox(805, 485, 0, 0, 0);
mySprite.graphics.clear(); // here we clean it
mySprite.graphics.beginGradientFill(GradientType.LINEAR, [colors.left, colors.right], [1, 1], [0x00, 0xFF], m, SpreadMethod.REFLECT);
mySprite.graphics.drawRoundRect(0,0,805,485, 0);
stage.setChildIndex(mySprite, 1);
}
function animateBackground(){
TweenMax.to(colors, 3, {hexColors:{left:newColor1, right:newColor2}, onUpdate:drawGradient, onComplete:reRandomize});
}
function reRandomize(){
color1 = newColor1;
color2 = newColor2;
newColor1 = Math.floor(Math.random()*0xFFFFFF + 1);
newColor2 = Math.floor(Math.random()*0xFFFFFF + 1);
animateBackground();
}
}
}
Code from Ship:
public class Ship extends MovieClip {
public function Ship() {
if (stage) {
init(null);
}else{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
public function init(e:Event) {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
this.addEventListener(Event.ENTER_FRAME, update_ship);
}
public function update_ship(e:Event){
x_vel = Direction_bar.dX*power;
y_vel = Direction_bar.dY*power;
this.x += x_vel;
this.y += y_vel;
if((10 < Math.abs(Direction_bar.dX) || 10 < Math.abs(Direction_bar.dY)) || ((0.9 < Math.abs(x_vel)||(0.9 < Math.abs(y_vel))))){
this.rotation = Direction_bar.point_direction;
}
rotation_now = this.rotation;
if(myShield != null){
if(myShield.visible == true){
myShield.alpha -= 0.0005;
if(myShield.alpha == 0){
myShield.visible = false;
myShield.alpha = 1;
}
}
}
}
Some basics that you have to know in order to understand what's going on.
It's a very common mistake to add things to stage.
Here's what the documentation of addChild says
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#addChild%28%29
objects should not be added to the Stage, directly, at all
I guess people add DispalyObjects to stage because they think it is
"the stage" that they see and interact with in the Flash authoring
environment. But it's not. stage.addChild() is not the same
thing as dragging a symbol from the library onto the screen. What by
default represents the main time line is the root property.
However, if you add anything to stage directly, its root property and its stage property both reference the same object,
which is regularly only referenced by stage. stage is some
container that your .swf is added to when running in the flash
player.
The documentation of addChildAt says this about the index:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#addChildAt%28%29
The child is added at the index position specified. An index of 0 represents the back (bottom) of the display list for this
DisplayObjectContainer object.
Applying these basics, the following happens:
FlashPlayer creates the stage object, instantiates your main class
and adds that instance to stage, it is the child with the index 0.
Among other things, stage.addChildAt(mySprite, 1); is executed,
adding mySprite as a second child to stage. With index of 1 it is
rendered in front of the object that is at index 0, which happens to
be the instance of your main class AKA your .swf file. I hope that
anything being rendered "outside the .swf file" illustrates well
enough why adding things to stage is not recommended.
Later, this.addChild(myShip); happens. (Which is actually the
proper way to do it; no need to use this here:addChild(myShip);
is all you need.) and adds the ship to the display list. Assuming all
of its parents are added to the display list as well, it will be
displayed.
But you still cannot see it, because you added mySprite in front of
the instance of your main class and filled it with a content in
drawGradient() which covers up everything else.
In all honesty, the best solution would be to start over from scratch.
Working with this code will not help you in any way. Even working yourself through it and making it work somehow will not make you understand anything better (except for how not to do things). It seems like the only motivation to modify this code to use classes was for the sake of doing it. Forcing such old code into the object oriented paradigm will not work very well. The benefits of oop will not be apparent, making this experience even more frustrating.
Last but not least, do not roll your own transition code. There are many libraries that do this (including flash's own Tween class http://www.republicofcode.com/tutorials/flash/as3tweenclass/ or the popular tweenlite http://greensock.com/tweenlite)
You could try adding an ADDED_TO_STAGE event. See this excellent explanation from the master of game programming
Understanding ADDED_TO_STAGE Event

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.

Shaking effect - Flash CS6 ActionScript3.0

This question is related to ActionScript 3.0 and Flash CS6
I am trying to make an object shake a bit in a certain for some seconds. I made it a "movieclip" and made this code:
import flash.events.TimerEvent;
var Machine_mc:Array = new Array();
var fl_machineshaking:Timer = new Timer(1000, 10);
fl_machineshaking.addEventListener (TimerEvent.TIMER, fl_shakemachine);
fl_machineshaking.start ();
function fl_shakemachine (event:TimerEvent):void {
for (var i = 0; i < 20; i++) {
Machine.x += Math.random() * 6 - 4;
Machine.y += Math.random() * 6 - 4;
}
}
When testing the movie I get multiple errors looking exactly like this one:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Historieoppgave_fla::MainTimeline/fl_shakemachine()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Also, the object doesnt shake, but it moves steadily upwards to the left a bit every tick.
To the point:
I wish to know how I stop the script after the object is not in the stage/scene anymore and also how to make it shake around, as I do not see what is wrong with my script, please help, thank you ^_^
AStupidNube brought up a great point about the original position. So adding that to shaking that should be a back and forth motion, so don't rely on random values that may or may not get you what you want. Shaking also has a dampening effect over time, so try something like this:
Link to working code
• http://wonderfl.net/c/eB1E - Event.ENTER_FRAME based
• http://wonderfl.net/c/hJJl - Timer Based
• http://wonderfl.net/c/chYC - Event.ENTER_FRAME based with extra randomness
**1 to 20 shaking items Timer Based code - see link above for ENTER_FRAME code••
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.text.TextField;
import flash.utils.Timer;
public class testing extends Sprite {
private var shakeButton:Sprite;
private var graphic:Sprite;
private var shakerPos:Array;
private var shakers:Array;
private var numShakers:int = 20;
private var dir:int = 1;
private var displacement:Number = 10;
private var shakeTimer:Timer;
public function testing() {
this.shakers = new Array();
this.shakerPos = new Array();
this.addEventListener(Event.ADDED_TO_STAGE, this.init);
}
private function init(e:Event):void {
this.stage.frameRate = 30;
this.shakeTimer = new Timer(33, 20);
this.shakeTimer.addEventListener(TimerEvent.TIMER, this.shake);
this.graphics.beginFill(0x333333);
this.graphics.drawRect(0,0,this.stage.stageWidth, this.stage.stageHeight);
this.graphics.endFill();
this.createShakers();
this.shakeButton = this.createSpriteButton("Shake ");
this.addChild(this.shakeButton);
this.shakeButton.x = 10;
this.shakeButton.y = 10;
this.shakeButton.addEventListener(MouseEvent.CLICK, this.shakeCallback);
}
private function createSpriteButton(btnName:String):Sprite {
var sBtn:Sprite = new Sprite();
sBtn.name = btnName;
sBtn.graphics.beginFill(0xFFFFFF);
sBtn.graphics.drawRoundRect(0,0,80,20,5);
var sBtnTF:TextField = new TextField();
sBtn.addChild(sBtnTF);
sBtnTF.text = btnName;
sBtnTF.x = 5;
sBtnTF.y = 3;
sBtnTF.selectable = false;
sBtn.alpha = .5;
sBtn.addEventListener(MouseEvent.MOUSE_OVER, function(e:Event):void { sBtn.alpha = 1 });
sBtn.addEventListener(MouseEvent.MOUSE_OUT, function(e:Event):void { sBtn.alpha = .5 });
return sBtn;
}
private function createShakers():void {
var graphic:Sprite;
for(var i:int = 0;i < this.numShakers;i++) {
graphic = new Sprite();
this.addChild(graphic);
graphic.graphics.beginFill(0xFFFFFF);
graphic.graphics.drawRect(0,0,10,10);
graphic.graphics.endFill();
// add a 30 pixel margin for the graphic
graphic.x = (this.stage.stageWidth-60)*Math.random()+30;
graphic.y = (this.stage.stageWidth-60)*Math.random()+30;
this.shakers[i] = graphic;
this.shakerPos[i] = new Point(graphic.x, graphic.y);
}
}
private function shakeCallback(e:Event):void {
this.shakeTimer.reset();
this.shakeTimer.start();
}
private function shake(e:TimerEvent):void {
this.dir *= -1;
var dampening:Number = (20 - e.target.currentCount)/20;
for(var i:int = 0;i < this.numShakers;i++) {
this.shakers[i].x = this.shakerPos[i].x + Math.random()*10*dir*dampening;
this.shakers[i].y = this.shakerPos[i].y + Math.random()*10*dir*dampening;
}
}
}
}
Now this is a linear dampening, you can adjust as you see fit by squaring or cubing the values.
You have to remember the original start position and calculate the shake effect from that point. This is my shake effect for MovieClips. It dynamically adds 3 variables (startPosition, shakeTime, maxShakeAmount) to it. If you use classes, you would add them to your clips.
import flash.display.MovieClip;
import flash.geom.Point;
function shake(mc:MovieClip, frames:int = 10, maxShakeAmount:int = 30) : void
{
if (!mc._shakeTime || mc._shakeTime <= 0)
{
mc.startPosition = new Point(mc.x, mc.y);
mc._shakeTime = frames;
mc._maxShakeAmount = maxShakeAmount;
mc.addEventListener(Event.ENTER_FRAME, handleShakeEnterFrame);
}
else
{
mc.startPosition = new Point(mc.x, mc.y);
mc._shakeTime += frames;
mc._maxShakeAmount = maxShakeAmount;
}
}
function handleShakeEnterFrame(event:Event):void
{
var mc:MovieClip = MovieClip(event.currentTarget);
var shakeAmount:Number = Math.min(mc._maxShakeAmount, mc._shakeTime);
mc.x = mc.startPosition.x + (-shakeAmount / 2 + Math.random() * shakeAmount);
mc.y = mc.startPosition.y + (-shakeAmount / 2 + Math.random() * shakeAmount);
mc._shakeTime--;
if (mc._shakeTime <= 0)
{
mc._shakeTime = 0;
mc.removeEventListener(Event.ENTER_FRAME, handleShakeEnterFrame);
}
}
You can use it like this:
// shake for 100 frames, with max distance of 15px
this.shake(myMc, 100, 15);
BTW: In Flash, you should enable 'permit debugging' in your 'publish settings' to have more detailed errors. This also gives back the line numbers where your code is breaking.
update:
Code now with time / maximum distance separated.
Here is a forked version of the chosen answer, but is a bit more flexible in that it allows you to set the frequency as well. It's also based on time as opposed to frames so you can think in terms of time(ms) as opposed to frames when setting the duration and interval.
The usage is similar to the chosen answer :
shake (clipToShake, durationInMilliseconds, frequencyInMilliseconds, maxShakeRange);
This is just an example of what I meant by using a TimerEvent as opposed to a ENTER_FRAME. It also doesn't require adding dynamic variables to the MovieClips you are shaking to track time, shakeAmount, and starting position.
public function shake(shakeClip:MovieClip, duration:Number = 3000, frequency:Number = 30, distance:Number = 30):void
{
var shakes:int = duration / frequency;
var shakeTimer:Timer = new Timer(frequency, shakes);
var startX:Number = shakeClip.x;
var startY:Number = shakeClip.y;
var shakeUpdate:Function = function(e:TimerEvent):void
{
shakeClip.x = startX + ( -distance / 2 + Math.random() * distance);
shakeClip.y = startY + ( -distance / 2 + Math.random() * distance);
}
var shakeComplete:Function = function(e:TimerEvent):void
{
shakeClip.x = startX;
shakeClip.y = startY;
e.target.removeEventListener(TimerEvent.TIMER, shakeUpdate);
e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, shakeComplete);
}
shakeTimer.addEventListener(TimerEvent.TIMER, shakeUpdate);
shakeTimer.addEventListener(TimerEvent.TIMER_COMPLETE, shakeComplete);
shakeTimer.start();
}
-4 <= Math.random() * 6 - 4 < 2
You add this offset to Machine.x 20 times, so chances for moving to the left is greater, than to the right.
It seems that you looking for something like this:
for each (var currentMachine:MovieClip in Machine_mc)
{
currentMachine.x += Math.random() * 6 - 3;
currentMachine.y += Math.random() * 6 - 3;
}

Game conversion from AS2 to AS3

I have an example of very simple shooter. But it on AS2. Here the source:
speed = 4;
depth = 0;
nose = 50;
_root.onMouseMove = function() {
updateAfterEvent();
xdiff = _root._xmouse-spaceShip._x;
ydiff = _root._ymouse-spaceShip._y;
angle = Math.atan2(ydiff, xdiff);
angle = angle*180/Math.PI;
spaceShip._rotation = angle;
};
_root.onMouseDown = function() {
angle = spaceShip._rotation;
angle = angle*Math.PI/180;
++depth;
name = "projectile"+depth;
_root.attachMovie("projectile", name, depth);
//projectile - it is bullet
_root[name]._x = spaceShip._x+nose*Math.cos(angle);
_root[name]._y = spaceShip._y+nose*Math.sin(angle);
_root[name].xmov = speed*Math.cos(angle);
_root[name].ymov = speed*Math.sin(angle);
_root[name].onEnterFrame = function() {
this._x += this.xmov;
this._y += this.ymov;
};
};
I want to do the same, but in as3.
I tried to convert. Here is what I have: PS - I'm newbie, please, don't get angry of the code below :)
var nose=55;
var angle;
var acc=1;
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursor);
function cursor(e:MouseEvent):void {
cross.x=mouseX;
cross.y=mouseY;
}
stage.addEventListener(Event.ENTER_FRAME, rotation2);
function rotation2(event:Event):void {
var xdiff=mouseX-spaceShip.x;
var ydiff=mouseY-spaceShip.y;
angle=Math.atan2(ydiff,xdiff);
angle=angle*180/Math.PI;
spaceShip.rotation=angle;
}
stage.addEventListener(MouseEvent.CLICK, shoot);
function shoot(event:MouseEvent):void {
angle = spaceShip.rotation;
angle = angle*Math.PI/180;
bullet.x=spaceShip.x+nose*Math.cos(angle);
bullet.y=spaceShip.y+nose*Math.sin(angle);
var xmov=acc*Math.cos(angle);
var ymov=acc*Math.sin(angle);
stage.addEventListener(Event.ENTER_FRAME, action);
function action(event:Event):void {
bullet.x+=xmov;
bullet.y+=xmov;
}
}
bullet appears, but only once, and did not move on the right path.
how to do that would be a lot of bullets, as in the example above?
attachMovie() is not the same as addChild().
MovieClip.attachMovie() creates a new symbol and add it to the MovieClip
DisplayObjectContainer.addChild() adds the specified DisplayObject to the container
Instead of calling (in AS2):
_root.attachMovie("projectile", name, depth);
You should use something like this (in AS3):
var proj:DisplayObject = new projectile();
proj.name = "projectile" + depth;
stage.addChild(proj);
Please note that there is no depth in AS3.
You could trick this by using addChildAt().
Thanks for the fast replying. I solve the problem this way:
I added this:
var bullet1:Bullet = new Bullet ();
addChild (bullet1);
And changed all "bullet" below on "bullet1".
Program is working now correctly.