AS3 ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller - actionscript-3

I am making a minions game. My minion's instance name is sideMinion. The bananas are falling and everything works fine, but my removeChild() doesn't work properly. The error I'm getting is
Error #2025: The supplied DisplayObject must be a child of the caller.
The removeChild() or the hitTestObject doesn't work properly.
This is what I have in my banana as. class:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.Event;
public class banana extends MovieClip {
var velX: Number = 0;
var velY: Number = 0;
var falling: Boolean = false;
var gravity: Number = 0;
public function banana() {
var timing: Timer = new Timer(25, 0);
timing.addEventListener(TimerEvent.TIMER, moveMe);
timing.start();
}
private function moveMe(event: TimerEvent)
{
x += velX;
y += velY;
if (falling) velY += gravity;
/* trace("[BANANA] position:", x, y, "speed:", velX, velY);*/
}
public function setSpeed(dx,dy) {
velX = dx;
velY = dy;
}
public function setSpot(atX,atY){
this.x=atX;
this.y=atY;
}
public function makeItFall (){
falling=true;
}
}
}
And in my main program:
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.Event;
var leftKey:Boolean;
var rightKey:Boolean;
var upKey:Boolean;
var downKey:Boolean;
var jump:Boolean = false;
var xvelocity:int = 9;
var yvelocity:int = 3;
var gravity:Number = 7;
stage.addEventListener(Event.ENTER_FRAME, changeVelocity);
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyDown);
function changeVelocity(evt:Event){
moveMinion();
yvelocity += gravity;
}
function moveMinion(){
if (leftKey == true){
sideMinion.x -= xvelocity;
sideMinion.left();
}
if (rightKey == true){
sideMinion.x += xvelocity;
sideMinion.right();
}
}
function checkKeyDown(e:KeyboardEvent){
if (e.keyCode == Keyboard.LEFT){
leftKey = true;
}
else if (e.keyCode == Keyboard.RIGHT){
rightKey = true;
}
}
function checkKeyUp(e:KeyboardEvent){
if (e.keyCode == Keyboard.LEFT){
leftKey = false;
}
else if (e.keyCode == Keyboard.RIGHT){
rightKey = false;
}
}
btnStart.addEventListener(MouseEvent.CLICK, makeItFall);
function makeItFall(e:MouseEvent){
var numBananas = 6;
var theBananas: Array = new Array();
theBananas = [];
for (var i = 0; i < numBananas; i++) {
var aBanana: banana = new banana();
theBananas.push(aBanana);
btnStart.visible=false;
aBanana.y=30;
theBananas[i].setSpot(Math.random()*450+50,Math.random()*200+20);
theBananas[i].setSpeed((Math.random()), 1);
stage.addChild(aBanana);
}
var health: uint= 1;
addEventListener(Event.ENTER_FRAME, pickUpBananas);
function pickUpBananas(event:Event){
for( var i= 0; i<theBananas.length; ++i){
if (sideMinion.hitTestObject(theBananas[i])){
removeChild(theBananas[i]);
health=health+1;
trace(health);
}
}
}
}
stop();
Edit : format code

As you are adding child to stage, you'll have to remove it also from stage:
stage.removeChild(theBananas[i]);
For future, in some situations you can also use parent property if you don't know the actual parent:
theBananas[i].parent.removeChild(theBananas[i]);
In your game, I assume you want also to remove the bananas from theBananas-array when you remove bananas from stage, so that your array wont end up having already deleted bananas. So, here's couple modifications:
for(var i:int = theBananas.length-1; i>-1; i--){ //inverted loop
if (sideMinion.hitTestObject(theBananas[i])){
stage.removeChild(theBananas[i]);
theBananas.splice(i,1); //removing it from the array
health=health+1;
trace(health);
}
}
Inverted loop obviously loops from last element all the way to the first one, becouse if you'd remove the first element from the array, then second element would 'jump' into its place and loop would skip it.
I hope we all will soon get to see your game! :)

Related

5006: An ActionScript file can not have more than one externally visible definition: AND TypeError: Error #1006: hitTestObject is not a function

I have 2 issues in this code.
The first is:
5006: An ActionScript file can not have more than one externally visible definition: Sprayer, bugs
I've put multiple Actionscripts together to create this, i've seperated out the classes and am hoping to play this on a frame from a symbol.
and the second relates to:
Error #1006: hitTestObject is not a function
For this i'm trying to get the aagun/Sprayer to lose health then lives if the bugs touch it, but i'm not sure why it's saying it's not a function. Am I using the wrong words?
Thanks for your help, here's the code
package Shooter{
import flash.display.*;
import flash.events.*;
import flash.utils.getTimer;
class Sprayer extends MovieClip{
const speed:Number = 150.0;
var lastTime:int; // animation time
function Sprayer() {
// initial location of gun
this.x = 275;
this.y = 340;
// movement
addEventListener(Event.ENTER_FRAME,moveGun);
}
function moveGun(event:Event) {
// get time difference
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// current position
var newx = this.x;
// move to the left
if (MovieClip(parent).leftArrow) {
newx -= speed*timePassed/1000;
}
// move to the right
if (MovieClip(parent).rightArrow) {
newx += speed*timePassed/1000;
}
// check boundaries
if (newx < 10) newx = 10;
if (newx > 540) newx = 540;
// reposition
this.x = newx;
}
// remove from screen and remove events
function deleteGun() {
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveGun);
}
}
}
package BigBug{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
class bugs extends MovieClip {
var dx:Number; // speed and direction
var lastTime:int; // animation time
function bugs(side:String, speed:Number, altitude:Number) {
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = 1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = 1; // not reverse
}
this.y = altitude; // vertical position
// choose a random plane
this.gotoAndStop(Math.floor(Math.random()*4+1));
// set up animation
addEventListener(Event.ENTER_FRAME,movePlane);
lastTime = getTimer();
}
function movePlane(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move plane
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deletePlane();
} else if ((dx > 0) && (x > 350)) {
deletePlane();
}
}
}
}
package Missiles{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
class Bullets extends MovieClip {
var dx:Number; // vertical speed
var lastTime:int;
function Bullets(x,y:Number, speed: Number) {
// set start position
this.x = x;
this.y = y;
// get speed
dx = speed;
// set up animation
lastTime = getTimer();
addEventListener(Event.ENTER_FRAME,moveBullet);
}
function moveBullet(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move bullet
this.x += dx*timePassed/1000;
// bullet past top of screen
if (this.x < 0) {
deleteBullet();
}
}
// delete bullet from stage and plane list
function deleteBullet() {
MovieClip(parent).removeBullet(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveBullet);
}
}
}
package MainGame{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
import Missiles.Bullets;
import Shooter.Sprayer;
import BigBug.bugs;
public class AirRaid extends MovieClip {
private var aagun:Sprayer;
private var airplanes:Array;
private var buggood:Array;
private var bullets:Array;
public var leftArrow, rightArrow:Boolean;
private var nextGbug:Timer;
private var nextPlane:Timer;
private var shotsLeft:int;
private var shotsHit:int;
public function startAirRaid() {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
// create gun
aagun = new Sprayer();
addChild(aagun);
// create object arrays
buggood = new Array();
airplanes = new Array();
bullets = new Array();
// listen for keyboard
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// look for collisions
addEventListener(Event.ENTER_FRAME,checkForHits);
// start planes flying
setNextPlane();
setNextGbug();
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .5) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*50+20;
var speed:Number = Math.random()*150+150;
// create plane
var p:bugs = new bugs(side,speed,altitude);
addChild(p);
airplanes.push(p);
// set time for next plane
setNextPlane();
}
public function setNextGbug() {
nextGbug = new Timer(1000+Math.random()*1000,1);
nextGbug.addEventListener(TimerEvent.TIMER_COMPLETE,newGbug);
nextGbug.start();
}
public function newGbug(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .5) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*50+20;
var speed:Number = Math.random()*150+150;
// create Gbug
var p:Good_bug = new Good_bug(side,speed,altitude);
addChild(p);
buggood.push(p);
// set time for next Gbug
setNextGbug();
}
// check for collisions
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=airplanes.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(airplanes[airplaneNum])) {
airplanes[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
shotsHit++;
showGameScore();
break;
}
}
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var Good_bugNum:int=buggood.length-1;Good_bugNum>=0;Good_bugNum--) {
if (bullets[bulletNum].hitTestObject(buggood[Good_bugNum])) {
buggood[Good_bugNum].GbugHit();
bullets[bulletNum].deleteBullet();
shotsHit--;
showGameScore();
break;
}
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
// key pressed
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = true;
} else if (event.keyCode == 39) {
rightArrow = true;
} else if (event.keyCode == 32) {
fireBullet();
}
}
// key lifted
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = false;
} else if (event.keyCode == 39) {
rightArrow = false;
}
}
// new bullet created
public function fireBullet() {
if (shotsLeft <= 0) return;
var b:Bullets = new Bullets(aagun.x,aagun.y,-300);
addChild(b);
bullets.push(b);
shotsLeft--;
showGameScore();
}
public function showGameScore() {
showScore.text = String("Score: "+shotsHit);
showShots.text = String("Shots Left: "+shotsLeft);
}
// take a plane from the array
public function removePlane(plane:bugs) {
for(var i in airplanes) {
if (airplanes[i] == plane) {
airplanes.splice(i,1);
break;
}
}
}
// take a Gbug from the array
public function removeGbug(Gbug:Good_bug) {
for(var i in buggood) {
if (buggood[i] == Gbug) {
buggood.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullets) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
// game is over, clear movie clips
public function endGame() {
// remove planes
for(var i:int=airplanes.length-1;i>=0;i--) {
airplanes[i].deletePlane();
}
for(var i:int=buggood.length-1;i>=0;i--) {
buggood[i].deleteGbug();
}
airplanes = null;
buggood = null;
aagun.deleteGun();
aagun = null;
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
removeEventListener(Event.ENTER_FRAME,checkForHits);
nextPlane.stop();
nextPlane = null;
nextGbug.stop();
nextGbug = null;
gotoAndStop("gameover");
}
}
}
1.
5006: An ActionScript file can not have more than one externally visible definition: Sprayer, bugs
As it says exactly: you can't have more than one public definition in a file. You have to either split the code to several files or move definitions, that you don't need public, out of the package.
This would be Ok in one file:
package
{
import flash.display.MovieClip;
// public is the default access modifier
public class Test1 extends MovieClip
{
public function Test1()
{
trace("test1");
var t2:Test2 = new Test2();
var t3:Test3 = new Test3();
}
}
}
// Test2 and Test3 are defined outside of the package, otherwise it wouldn't compile.
// These definitions will only be visible to code in this file.
import flash.display.MovieClip;
class Test2 extends MovieClip
{
public function Test2()
{
trace("test2");
}
}
class Test3 extends MovieClip
{
public function Test3()
{
trace("test3");
}
}
2.
Error #1006: hitTestObject is not a function
This usually means that hitTestObject() is not defined on the object (or it's ancestors) you are trying to call it from (although there could be different kinds of errors for that).
hitTestObject() is accessed in two ways in your code: airplanes.hitTestObject() and bullets[bulletNum].hitTestObject(). You will have to debug your code to see what is actually airplanes and bullets[bulletNum], what types they are and whether they inherit hitTestObject() method. You could at least trace() them.

Error #2025: The supplied DisplayObject must be a child of the caller - Game Looping when after gotoAndStop

So ok Im somewhat new to flash im more of a java man myself but anyway I keep getting this error and all the solutions ive been find either don't work or they break the games collision
Here's the Code
stop();
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
import flash.events.Event;
import flash.events.TimerEvent;
var playerobj:player;
var nextObject:Timer;
var objects:Array = new Array();
var score:int = 0;
const speed:Number = 9.0;
playerobj = new player();
playerobj.y = 650;
addChild(playerobj);
setNextObject();
addEventListener(Event.ENTER_FRAME, moveObjects);
function setNextObject()
{
nextObject = new Timer(1000+Math.random()*1000,1);
nextObject.addEventListener(TimerEvent.TIMER_COMPLETE,newObject);
nextObject.start();
}
function newObject(e:Event)
{
var newObject:AI;
newObject = new AI();
newObject.x = Math.random() * 480;
addChild(newObject);
objects.push(newObject);
setNextObject();
}
function moveObjects(e:Event)
{
for (var i:int=objects.length-1; i>=0; i--)
{
objects[i].y += speed;
if (objects[i].y > 800)
{
removeChild(objects[i]);
score = score + 10000;
objects.splice(i,1);
}
if (objects[i].hitTestObject(playerobj))
{
cleanUp();
}
}
playerobj.x = mouseX;
}
function cleanUp():void
{
while (this.numChildren > 0)
{
removeChildAt(0);
}
nextObject.stop();
gotoAndStop(4);
stop();
}
It must be somehow related to this problem but whenever gotoAndStop is called the game seems to loop around back into the frame not really sure why, Thanks for your help
In the cleanup function, right after declaring it, you should remove the ENTER_FRAME event listener. Also, I would stop the timer before removing childs and I would just remove the objects you added to stage dynamically. And the stop() in the cleanup function is redundant.
function cleanUp():void {
removeEventListener(Event.ENTER_FRAME, moveObjects);
nextObject.stop();
for(var i:uint = 0; i < objects.length; i++){
removeChild(objects[i]);
}
removeChild(playerObj)
gotoAndStop(4);
}
Also, it's better to keep minimal code in the timeline and move as much as you can in classes.
the error is in the cleanUp()
function moveObjects(e:Event)
{
for (var i:int=objects.length-1; i>=0; i--)
{
objects[i].y += speed;
if (objects[i].y > 800)
{
removeChild(objects[i]);
score = score + 10000;
objects.splice(i,1);
}
if (objects[i].hitTestObject(playerobj))
{
cleanUp();
}
}
//playerobj no more exists if cleanUp() is called, move this line above cleanUp();
//playerobj.x = mouseX;
//or inside cleanUp() put that line
//removeEventListener(Event.ENTER_FRAME, moveObjects);
}

error 1118: Implicit coercion of a value with static type flash.display:DisplayObject to a possibly unrelated type flash.display:MovieClip

Building a top down shooter, and after fixing some bugs an making everything work i am left with only one more.
error 1118: Implicit coercion of a value with static type flash.display:DisplayObject to a possibly unrelated type flash.display:MovieClip.
This is the Level.as where all the object are loaded
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.utils.Timer;
import flash.text.TextField;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.utils.*;
import flash.display.Shape;
import flash.display.DisplayObject
/**
*
*/
public class Level extends Sprite
{
//these booleans will check which keys are down
public var leftIsPressed:Boolean = false;
public var rightIsPressed:Boolean = false;
public var upIsPressed:Boolean = false;
public var downIsPressed:Boolean = false;
//how fast the character will be able to go
public var speed:Number = 5;
public var vx:Number = 0;
public var vy:Number = 0;
//how much time before allowed to shoot again
public var cTime:int = 0;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 12;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 16;
//the spaceAuto's score
public var score:int = 0;
//this movieclip will hold all of the bullets
public var bulletContainer:MovieClip = new MovieClip();
//whether or not the game is over
public var gameOver:Boolean = false;
public var SpaceAuto:spaceAuto = new spaceAuto;
// publiek toegangkelijke verwijzing naar deze class
public static var instance:Level;
public var particleContainer:MovieClip = new MovieClip();
// constructor code
public function Level()
{
instance = this;
SpaceAuto.x = 135;
SpaceAuto.y = 350;
addChild(this.SpaceAuto);
addChild(this.bulletContainer);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, generateParticles);
//checking if there already is another particlecontainer there
if(!contains(particleContainer))
{
//this movieclip will hold all of the particles
addChild(this.particleContainer);
}
}
function keyDownHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = true; break;
case Keyboard.RIGHT : rightIsPressed = true; break;
case Keyboard.UP : upIsPressed = true; break;
case Keyboard.DOWN : downIsPressed = true; break;
}
if(e.keyCode == 32 && shootAllow)
{
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = SpaceAuto.x + SpaceAuto.width/2 - newBullet.width/2;
newBullet.y = SpaceAuto.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
}
}
function keyUpHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = false; break;
case Keyboard.RIGHT : rightIsPressed = false; break;
case Keyboard.UP : upIsPressed = false; break;
case Keyboard.DOWN : downIsPressed = false; break;
}
}
function enterFrameHandler(e:Event):void {
vx = -int(leftIsPressed)*speed + int(rightIsPressed)*speed;
vy = -int(upIsPressed)*speed + int(downIsPressed)*speed;
SpaceAuto.x += vx;
SpaceAuto.y += vy;
if(cTime < cLimit)
{
cTime ++;
trace("++")
}
else
{
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 0;
}
//adding enemies to stage
if(enemyTime < enemyLimit)
{
//if time hasn't reached the limit, then just increment
enemyTime ++;
}
else
{
//defining a variable which will hold the new enemy
var newEnemy = new Enemy();
//making the enemy offstage when it is created
newEnemy.y = -1 * newEnemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
newEnemy.x = int(Math.random()*(stage.stageWidth - newEnemy.width));
//then add the enemy to stage
addChild(newEnemy);
//and reset the enemyTime
enemyTime = 0;
}
//updating the score text
txtScore.text = 'Score: '+score;
if (gameOver == true)
{
loadScreenThree();
}
}
function generateParticles(event:Event):void
{
//so we don't do it every frame, we'll do it randomly
if(Math.random()*10 < 2){
//creating a new shape
var mcParticle:Shape = new Shape();
//making random dimensions (only ranges from 1-5 px)
var dimensions:int = int(Math.random()*5)+1;
//add color to the shape
mcParticle.graphics.beginFill(0x999999/*The color for shape*/,1/*The alpha for the shape*/);
//turning the shape into a square
mcParticle.graphics.drawRect(dimensions,dimensions,dimensions,dimensions);
//change the coordinates of the particle
mcParticle.x = int(Math.random()*stage.stageWidth);
mcParticle.y = -10;
//adding the particle to stage
particleContainer.addChild(mcParticle);
}
//making all of the particles move down stage
for(var i:int=particleContainer.numChildren - 1; i>=0; i--){
//getting a certain particle
var theParticle:DisplayObject = particleContainer.getChildAt(i);
//it'll go half the speed of the character
theParticle.y += speed*.5;
//checking if the particle is offstage
if(theParticle.y >= 400){
//remove it
particleContainer.removeChild(theParticle);
}
}
}
/**
* eventhandler voor als je op de tweede knop klikt
*/
private function loadScreenThree():void
{
// eerst opruimen!
cleanListeners();
// dan naar ander scherm
Project.instance.switchScreen( "derde" );
}
private function cleanListeners():void
{
stage.removeEventListener(Event.ENTER_FRAME, generateParticles);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
}}
Where it goes wrong is in the Enemy Class in the eFrame Function. Here a loop runs trough the array bulletContainer from Level.as. A new variable is made and it should consist of the bullet that is in the loop out of the bulletContainer, and here comes the error in place
package{
//we have to import certain display objects and events
import Level;
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
//this just means that Enemy will act like a MovieClip
public class Enemy extends MovieClip
{
//VARIABLES
//this will act as the root of the document
//so we can easily reference it within the class
private var _root:Object;
//how quickly the enemy will move
private var speed:int = 5;
//this function will run every time the Bullet is added
//to the stage
public function Enemy()
{
//adding events to this class
//functions that will run only when the MC is added
addEventListener(Event.ADDED, beginClass);
//functions that will run on enter frame
addEventListener(Event.ENTER_FRAME, eFrame);
}
private function beginClass(event:Event):void
{
_root = Sprite(root);
}
private function eFrame(event:Event):void
{
//moving the bullet up screen
y += speed;
//making the bullet be removed if it goes off stage
if(this.y > 400)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
}
//checking if it is touching any bullets
//we will have to run a for loop because there will be multiple bullets
for(var i:int = 0;i<Level.instance.bulletContainer.numChildren;i++)
{
//numChildren is just the amount of movieclips within
//the bulletContainer.
trace("LOOOOOOOOOP");
trace(Level.instance.bulletContainer.getChildAt(i));
//we define a variable that will be the bullet that we are currently
//hit testing.
var bulletTarget:Sprite = Level.instance.bulletContainer.getChildAt(i);
//now we hit test
if(hitTestObject(bulletTarget))
{
//remove this from the stage if it touches a bullet
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
//also remove the bullet and its listeners
Level.instance.bulletContainer.removeChild(bulletTarget);
//bulletTarget.removeListeners();
//up the score
Level.instance.score += 5;
}
}
//hit testing with the user
if(hitTestObject(Level.instance.SpaceAuto))
{
//losing the game
trace("DOOOOOD");
removeListeners();
this.parent.removeChild(this);
this.removeEventListener(Event.ENTER_FRAME, eFrame);
Level.instance.gameOver = true;
}
}
public function removeListeners():void
{
this.removeEventListener(Event.ENTER_FRAME, eFrame);
}
}}
i have tried make it Sprite or anything else but i just dont know how to fix this so it wil take the bullet so i van see if it hits the Enemy
var bulletTarget:Sprite = Level.instance.bulletContainer.getChildAt(i);
getChildAt will return a DisplayObject type, and hitTestObject requires a parameter with DisplayObject type.
So try this in your Enemy's eFrame function.
var bulletTarget:DisplayObject = Level.instance.bulletContainer.getChildAt(i);

Character getting faster everytime I reset my game from gameover screen in action script 3

My game starts with a start frame. click a button to the game. if I hit an object I go to game over screen. Everytime I hit the start over button on the game over screen my characters controls get faster. I have set no variables for speed, simply just "mc_guy.x +=3" or .y , etc. If I had to say by how much faster I would want to say that the speed doubles.
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
//prevent game loop
stop();
// event listeners for movement
mc_Guy.addEventListener(Event.ENTER_FRAME, update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownGuy);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUpGuy);
// this array holds references to all the keys
var keys:Array = [];
//initiate default values
fuelGauge.height = 100;
//Gravity
addEventListener(Event.ENTER_FRAME,Gravity)
var GyAmt:Number = 5;
function Gravity(e:Event){
mc_Guy.y += GyAmt;
if (gameFloor.hitTestObject(mc_Guy)){
mc_Guy.y = gameFloor.y;}
else if (gameFloor2.hitTestObject(mc_Guy)){
mc_Guy.y = gameFloor2.y;}
else if (gameFloor3.hitTestObject(mc_Guy)){
mc_Guy.y = gameFloor3.y;}}
// the event listeners
function update(e:Event):void
{
if (keys[Keyboard.RIGHT])
{
mc_Guy.x += 3;
}
if (keys[Keyboard.LEFT])
{
mc_Guy.x -= 3;
}
if (keys[Keyboard.SPACE]){
mc_Guy.y -= 10;
//drain fuel
fuelGauge.height -= 1;
gaugePercent.text = String(fuelGauge.height)
if (fuelGauge.height == 0){
nextFrame();}}
}
function onKeyDownGuy(e:KeyboardEvent):void
{
keys[e.keyCode] = true;
}
function onKeyUpGuy(e:KeyboardEvent):void
{
keys[e.keyCode] = false;
}
//Array storing each wall
var MC_wall:Array = new Array(mc_Wall,mc_Wall2,mc_Wall5,
mc_Wall6,mc_Wall7,mc_Wall8,mc_Wall9,mc_Wall10,mc_Wall11,mc_Wall12, mc_Wall13)
//Collision Detection
addEventListener(Event.ENTER_FRAME,loop);
function loop(e:Event){
var i:Number = 0;
do {
if (MC_wall[i].hitTestObject(mc_Guy)){
nextFrame();}
i++;
} while (i < MC_wall.length);
/* for (var i:Number = 0; i < MC_wall.length; i++){
if (MC_wall[i].hitTestObject(mc_Guy)){
nextFrame();}
}*/
if(mc_Guy.hitTestPoint(mc_WallRun.x, mc_WallRun.y, false)){
nextFrame();}
else if(mc_Guy.hitTestObject(fuelPowerup)){
removeChild(fuelPowerup);
fuelGauge.height = 100;
gaugePercent.text = String(fuelGauge.height)}
else if(mc_Guy.hitTestObject(doorKey)){
removeChild(doorKey)
//open door
mc_Wall13.height -=20
mc_Wall13.y -= 10
}
}
//Object Movement
addEventListener(Event.ENTER_FRAME, onEnterFrame);
var spinSpeed:Number=6;
var axisMove:Number = 90;
var axisMovement:Number = 3;
function onEnterFrame(event:Event):void
{
mc_WallRun.rotation+=spinSpeed;
//count the movement on axis and move
axisMove -= 3;
mc_Wall9.x += axisMovement;
gameFloor3.x += axisMovement * .9;
if(axisMove <= 0){
axisMove += 90
axisMovement = axisMovement*-1
}
}
Gameover frame:
import flash.events.MouseEvent;
stop();
restartGame.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
function playAgain(event:MouseEvent):void{
prevFrame();
}
It sounds like when you restart your game
mc_Guy.addEventListener(Event.ENTER_FRAME, update);
is called again, without removing the previously added listener.
So update is now called two times on Event.ENTER_FRAME, and then once more per frame per game reset, causing the guy to move faster.

Actionscript 3 Making the character to Jump

I am making a platformer game. But I am having issue because whenever I pressed the spacebar to jump, the character will stuck in the mid-air. However, I can resolved the problem by holding spacebar and the character will land.
The issue is at mainJump() located inside Boy class.
I seen many people solved the problem by using action timeline, but my main problem is, are there anyway I can solve the problem by using an external class?
Main class
package
{
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.*;
public class experimentingMain extends MovieClip
{
var count:Number = 0;
var myTimer:Timer = new Timer(10,count);
var classBoy:Boy;
//var activateGravity:gravity = new gravity();
var leftKey, rightKey, spaceKey, stopAnimation:Boolean;
public function experimentingMain()
{
myTimer.addEventListener(TimerEvent.TIMER, scoreUp);
myTimer.start();
classBoy = new Boy();
addChild(classBoy);
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressTheDamnKey);
stage.addEventListener(KeyboardEvent.KEY_UP, liftTheDamnKey);
}
public function pressTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = true;
stopAnimation = false;
}
if (event.keyCode == 39)
{
rightKey = true;
stopAnimation = false;
}
if (event.keyCode == 32)
{
spaceKey = true;
stopAnimation = true;
}
}
public function liftTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = false;
stopAnimation = true;
}
if (event.keyCode == 39)
{
rightKey = false;
stopAnimation = true;
}
if (event.keyCode == 32)
{
spaceKey = false;
stopAnimation = true;
}
}
public function scoreUp(event:TimerEvent):void
{
scoreSystem.text = String("Score : "+myTimer.currentCount);
}
}
}
Boy class
package
{
import flash.display.*;
import flash.events.*;
public class Boy extends MovieClip
{
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 5;
//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 40;
//the current speed of the jump;
var jumpSpeed:Number = 0;
var theCharacter:MovieClip;
var currentX,currentY:int;
public function Boy()
{
this.x = 600;
this.y = 540;
addEventListener(Event.ENTER_FRAME, boyMove);
}
public function boyMove(event:Event):void
{
currentX = this.x;
currentY = this.y;
if (MovieClip(parent).leftKey)
{
currentX += mainSpeed;
MovieClip(this).scaleX = 1;
}
if (MovieClip(parent).rightKey)
{
currentX -= mainSpeed;
MovieClip(this).scaleX = -1;
}
if (MovieClip(parent).spaceKey)
{
mainJump();
}
this.x = currentX;
this.y = currentY;
}
public function mainJump():void
{
currentY = this.y;
if (! mainJumping)
{
mainJumping = true;
jumpSpeed = jumpSpeedLimit * -1;
currentY += jumpSpeed;
}
else
{
if (jumpSpeed < 0)
{
jumpSpeed *= 1 - jumpSpeedLimit / 250;
if (jumpSpeed > -jumpSpeedLimit/12)
{
jumpSpeed *= -2;
}
}
}
if (jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit)
{
jumpSpeed *= 1 + jumpSpeedLimit / 120;
}
currentY += jumpSpeed;
if (currentY >= stage.stageHeight - MovieClip(this).height)
{
mainJumping = false;
currentY = stage.stageHeight - MovieClip(this).height;
}
}
}
}
First of all, formalize your code, eliminating sassy things like 'pressTheDamnKey,' which doesn't even describe the function very well because a function cannot press a key. That is an event handler and should be named either keyDownHandler or onKeyDown, nothing else.
Secondly, you rarely want to do any actual work in event handlers beyond the immediate concerns of the event data. Instead call out to the function which does the actual work. A handler handles the event, then calls the code which does the work. This separates out concerns nicely for when you want something else to be able to also make the little boy animate besides the enterFrameHandler, like perhaps a mouse.
I can imagine your trace log is getting filled up pretty quickly with "Score" lines since your timer is firing 100 times a second (10 milliseconds per). I would change that to not fire on a timer, but to be refreshed when the score actually changes.
The problem with the jumping, aside from spaghetti code, is that you are basing his movements upon whether the key is pressed or not by saving the state of the key press in a variable and having him continually inspect it. This is bad for a couple of reasons: 1. he should not need to reach out to his environment for information, it should be given to him by whatever object owns him or by objects that are responsible for telling him and 2. It requires you to continually hold down the spacebar or he will stop moving, since he checks to see if it is being held down (see problem 1).
I will address all these issues below, leaving out the scoring, which is another matter altogether.
package
{
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.*;
// Sprite is preferred if you are not using the timeline
public class Application extends Sprite
{
private var boy:Boy;
public function Application()
{
boy = new Boy();
addChild(boy);
boy.x = 600; // set these here, not in the boy
boy.y = 540;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler );
}
public function keyDownHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case 32: boy.jump();
break;
case 37: boy.moveLeft();
break;
case 39: boy.moveRight();
break;
default:
// ignored
break;
}
}
public function keyUpHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
// ignored for jumping (32)
case 37: // fall through
case 39: boy.stop();
break;
default:
// ignored
break;
}
}
}//class
}//package
package
{
import flash.display.*;
import flash.events.*;
// It is assumed that there is an asset in the library
// that is typed to a Boy, thus it will be loaded onto
// the stage by the owner
public class Boy extends Sprite
{
private var horzSpeed :Number = 0;
private var vertSpeed :Number = 0;
private var floorHeight :Number;
private var jumpHeight :Number;
private var amJumping :Boolean = false;
public function Boy()
{
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
public function moveLeft():void
{
horzSpeed = -1;
}
public function moveRight():void
{
horzSpeed = 1;
}
public function stop():void
{
horzSpeed = 0;
}
public function jump():void
{
if (amJumping) return;
floorHeight = y;
jumpHeight = floorHeight + 20;
vertSpeed = 2;
amJumping = true;
animateJump();
}
private function enterFrameHandler(event:Event):void
{
animate();
}
private function animate():void
{
x += horzSpeed;
if( amJumping )
{
animateJump();
}
}
// Doing a simple version for this example.
// If you want an easier task of jumping with gravity,
// I recommend you employ Greensock's superb
// TweenLite tweening library.
private function animateJump():void
{
y += vertSpeed;
if( y >= jumpHeight )
{
y = jumpHeight;
vertSpeed = -2;
}
else if( y <= floorHeight )
{
y = floorHeight;
amJumping = false;
}
}
}//class
}//package
Another way to approach this, and probably the better way long-term, is for the boy to not even be responsible for moving himself. Instead, you would handle that in the parent, his owner or some special Animator class that is responsible for animating things on schedule. In this even more encapsulated paradigm, the boy is only responsible for updating his own internal look based upon the outside world telling him what is happening to him. He would no longer handle jumping internally, but instead would be responsible for doing things like animating things he owns, like his arms and legs.
You've got a mainJumping variable that is only true while the jump is running. Why not just use that?
if (MovieClip(parent).spaceKey || mainJumping)
{
mainJump();
}