Can I get some tips With My Inventory system for my game. I want to use an object in my inventory with another object (like a Key to a Door) - actionscript-3

This is my Main Class:
package {
import flash.display.*;
public class InventoryDemo extends MovieClip {
var inventory:Inventory;
public function InventoryDemo() {
}
public function initialiseInventory():void
{
inventory = new Inventory(this);
inventory.makeInventoryItems([d1,d2]);
}
}
}
I used a sprite indicator to show that the items are inside the inventory.
And this is my child class:
package {
import flash.display.*;
import flash.events.*;
public class Inventory
{
var itemsInInventory:Array;
var inventorySprite:Sprite;
public function Inventory(parentMC:MovieClip)
{
itemsInInventory = new Array ;
inventorySprite = new Sprite ;
inventorySprite.x = 50;
inventorySprite.y = 360;
parentMC.addChild(inventorySprite);
}
function makeInventoryItems(arrayOfItems:Array)
{
for (var i:int = 0; i < arrayOfItems.length; i++)
{
arrayOfItems[i].addEventListener(MouseEvent.CLICK,getItem);
arrayOfItems[i].buttonMode = true;
}
}
function getItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
itemsInInventory.push(item);
inventorySprite.addChild(item);
item.x = itemsInInventory.length - 1 * 40;
item.y = 0;
item.removeEventListener(MouseEvent.CLICK,getItem);
item.addEventListener(MouseEvent.CLICK,useItem);
}
function useItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
trace(("Use Item:" + item.name));
}
}
}
Currently i can only click and trace the output, I was wondering how i can drag the sprite and use it to another object...like a key to unlock a door. Big thanks, btw im new in as3 and im trying to learn from stack overflow.

item.addEventListener(MouseEvent.CLICK,useItem);
var drag:Boolean;
function useItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
trace(("Use Item:" + item.name));
if(drag == false)
{
item.startDrag();
drag = true;
}else{
item.stopDrag();
drag = false;
findAction(e);
}
}
function findAction(e)
{
// Check the position of the key relative to the door.
}
Haven't really checked it but it'd probably work if you did something similar.

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.

AS3 How to remove objects from the stage from various classes

So I'm Creating a game that generates different types of fish. I have the main class initilize everything then the fish are generated with another class. I then have another class listen for when they are added to the stage that controls their movement. After the fish leaves the scene I have gotten them to be deleted but I cannot get them all to be deleted once the fish is clicked. I have a listener that gets when a fish is clicked but I am having trouble deleting all the other generated fish so that I can load the fish information.
I probably have tons of problems but here is my Main class:
package
{
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import Crappie;
/*import Bass;
import Bluegill;
import LongGar;
import Muskellunge;
import Perch;
import PumpkinSeed;
import ShortGar;
import SpotGar;*/
import GenerateFish;
public class FishGame extends MovieClip
{
private var randomFish:Number;
public function FishGame() //First function to be called
{
startMenu();
}
public function startMenu() //Loads the start menu
{
gotoAndStop("Start Menu");
StartButton.addEventListener(MouseEvent.CLICK, gotoStartGame);
}
private function gotoStartGame(evt:MouseEvent) //links to the start of th game
{
StartButton.removeEventListener(MouseEvent.CLICK, gotoStartGame);
gotoAndStop("Game");
game();
}
public function game() /generates fish
{
var genFish:GenerateFish = new GenerateFish();
this.addChild(genFish);
var genFish2:GenerateFish = new GenerateFish();
this.addChild(genFish2);
}
//This is where I need help. All the fish are children of other class. I tried deleting them in their own class but it seems like it would work best if it was in this class but I'm having trouble calling this class.
public function removeFish()
{
trace("Here");
}
}
}
Here is the generating fish class:
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.display.*;
import Crappie;
//import Bass;
//import Bluegill;
//import LongGar;
//import Muskellunge;
//import Perch;
//import PumpkinSeed;
//import ShortGar;
//import SpotGar;
import FishGame;
public class GenerateFish extends MovieClip {
private var randomFish:Number;
public function GenerateFish() //When this is added via addchild it adds a fish
{
this.addEventListener(Event.ADDED_TO_STAGE, addFish, false, 0, true);
//addFish();
}
private function addFish(e:Event) //adds fish to scrence
{
this.removeEventListener(Event.ADDED_TO_STAGE, addFish);
randomFish = Math.floor(Math.random() * 2);
randomFish = 0; //for testing purposes
switch(randomFish)
{
case 0:
var crappie:Crappie = new Crappie();
this.addChild(crappie); //Calls the crappy funciton
break;
case 1:
var longgar:LongGar = new LongGar();
this.addChild(longgar);
break;
case 2:
var bluegill:Bluegill = new Bluegill();
this.addChild(bluegill);
break;
case 3:
var spotgar:SpotGar = new SpotGar();
this.addChild(spotgar);
break;
case 4:
var muskellunge:Muskellunge = new Muskellunge();
this.addChild(muskellunge);
break;
case 5:
var pumpkinseed:PumpkinSeed = new PumpkinSeed();
this.addChild(pumpkinseed);
break;
case 6:
var bass:Bass = new Bass();
this.addChild(bass);
break;
case 7:
var perch:Perch = new Perch();
this.addChild(perch);
break;
case 8:
var pike:Pike = new Pike();
this.addChild(pike);
break;
default:
break;
}
}
}
}
And here is one of the specific fish classes:
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.*;
import FishGame;
import GenerateFish;
public class Crappie extends MovieClip
{
private var Speed:Number;
private var randomBoolean:Boolean = (Math.random() > .5) ? true : false;
private var fishOnScreen:Boolean = false;
//public var remFish:FishGame = new FishGame();
public function Crappie() //Adds event listeners to control the fish
{
this.addEventListener(Event.ADDED_TO_STAGE, Setup, false, 0, true);
this.addEventListener(MouseEvent.CLICK, GoToFishInfo);
fishOnScreen =true;
}
public function GoToFishInfo(evt:MouseEvent):void //When fish is clicked Info pops up. It is here i want every fish to be deleted.
{
this.removeEventListener(Event.ADDED_TO_STAGE, Setup);
/*while (MovieClip(root).numChildren >= 1) //What I tried to delete all objects
{
MovieClip(root).removeChildAt(1);
}*/
var remFish:FishGame = new FishGame(); //Creates The SWF file file:///FishGame/classes/FishGame.swf contains invalid data.
remFish.removeFish();
MovieClip(root).gotoAndStop("FishInfo", "Scene 1");
var crappieinfo:CrappieInfo = new CrappieInfo();
stage.addChild(crappieinfo);
crappieinfo.x = 512;
crappieinfo.y = 384;
crappieinfo.alpha = 100;
}
private function Setup(e:Event) //Setup the fish position and adds info for movement
{
var randomBoolean:Boolean = (Math.random() > .5) ? true : false;
//true forwards
//false is backwards
if (randomBoolean)
{
this.x = 1030;
}
else
{
this.scaleX = -1;
this.x = -10;
}
this.y = this.GetRandomYPosition();
this.alpha = 100;
this.addEventListener(Event.ENTER_FRAME, MoveCircle);
Speed = GetRandomSpeed();
if (randomBoolean)
{
Speed *= -1
}
}
private function GetRandomSpeed():Number
{
return (Math.floor(Math.random() * 5) +5);
}
private function GetRandomYPosition():Number
{
//
//basic formula: Math.floor(Math.random()*(1+High-Low))+Low;
//
return (Math.floor(Math.random() * (650-this.height)) + 230);
}
public function MoveCircle(e:Event) //Moves the fish
{
if (fishOnScreen)
{
this.x += Speed;
if (this.x >1024 || this.x < -10 || this.y >768 || this.y < 200)
{
var genExtraFish:GenerateFish = new GenerateFish();
stage.addChild(genExtraFish);
this.parent.removeChild(this);
fishOnScreen = false;
this.removeEventListener(MouseEvent.CLICK, GoToFishInfo);
}
}
}
}
}
Thanks I'd appreciate all the help I can get!
////////
//Edit//
////////
I have modified my main class to package
{
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import BaseFish;
import GenerateFish;
public class FishGame extends MovieClip
{
private var randomFish:Number;
private var basefish:BaseFish = new BaseFish();
public function FishGame()
{
startMenu();
}
public function startMenu()
{
gotoAndStop("Start Menu");
StartButton.addEventListener(MouseEvent.CLICK, gotoStartGame);
}
private function gotoStartGame(evt:MouseEvent)
{
StartButton.removeEventListener(MouseEvent.CLICK, gotoStartGame);
gotoAndStop("Game");
basefish.StartFish();
}
}
}
And I Created the basefish class as so:
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.*;
import FishGame;
public class BaseFish extends MovieClip
{
public var FishOnScreen:Array = new Array();
public var FishSpeed:Array = new Array();
private var Speed:Number;
private var randomBoolean:Boolean = (Math.random() > .5) ? true : false;
public var NumFish:int = -1;
private var randomFish:Number;
public function BaseFish()
{
}
public function StartFish()
{
addFish(5);
this.addEventListener(Event.ENTER_FRAME, MoveCircle);
}
public function addFish(NumAdd:Number)
{
for (var i:Number = 0; i < NumAdd; i++)
{
randomFish = Math.floor(Math.random() * 2);
randomFish = 0;
switch(randomFish)
{
case 0:
var crappie:Crappie = new Crappie();
this.addChild(crappie);
crappie.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(crappie);
trace(FishOnScreen[1]);
Setup(crappie);
NumFish += 1;
break;
case 1:
var longgar:LongGar = new LongGar();
this.addChild(longgar);
longgar.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(longgar);
Setup(longgar);
NumFish += 1;
break;
case 2:
var bluegill:Bluegill = new Bluegill();
this.addChild(bluegill);
bluegill.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(bluegill);
Setup(bluegill);
NumFish += 1;
break;
case 3:
var spotgar:SpotGar = new SpotGar();
this.addChild(spotgar);
spotgar.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(spotgar);
Setup(spotgar);
NumFish += 1;
break;
case 4:
var muskellunge:Muskellunge = new Muskellunge();
this.addChild(muskellunge);
muskellunge.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(muskellunge);
Setup(muskellunge);
NumFish += 1;
break;
case 5:
var pumpkinseed:Pumpkinseed = new Pumpkinseed();
this.addChild(pumpkinseed);
pumpkinseed.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(pumpkinseed);
Setup(pumpkinseed);
NumFish += 1;
break;
case 6:
var bass:Bass = new Bass();
this.addChild(bass);
bass.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(bass);
Setup(bass);
NumFish += 1;
break;
case 7:
var perch:Perch = new Perch();
this.addChild(perch);
perch.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(perch);
Setup(perch);
NumFish += 1;
break;
case 8:
var pike:Pike = new Pike();
this.addChild(pike);
pike.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(pike);
Setup(pike);
NumFish += 1;
break;
default:
this.addChild(crappie);
crappie.addEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.push(crappie);
Setup(crappie);
NumFish += 1;
break;
}
}
}
private function Setup(mc: MovieClip)
{
var randomBoolean:Boolean = (Math.random() > .5) ? true : false;
//true forwards
//false is backwards
if (randomBoolean)
{
MovieClip(mc).x = 1030;
}
else
{
MovieClip(mc).scaleX = -1;
MovieClip(mc).x = -10;
}
MovieClip(mc).y = GetRandomYPosition();
MovieClip(mc).alpha = 100;
FishSpeed[NumFish] = GetRandomSpeed();
if (randomBoolean)
{
FishSpeed[NumFish] *= -1
}
}
private function GetRandomSpeed():Number
{
return (Math.floor(Math.random() * 5) +5);
}
private function GetRandomYPosition():Number
{
//
//basic formula: Math.floor(Math.random()*(1+High-Low))+Low;
//
return (Math.floor(Math.random() * (650-this.height)) + 230);
}
public function MoveCircle(e:Event)
{
//trace(FishOnScreen.length);
for (var i:Number = 0; i < FishOnScreen.length; i++)
{
if (FishOnScreen[i]!=null)
{
MovieClip(FishOnScreen[i]).x += FishSpeed[i];
if (MovieClip(FishOnScreen[i]).x >1024 || MovieClip(FishOnScreen[i]).x < -10 || MovieClip(FishOnScreen[i]).y >768 || MovieClip(FishOnScreen[i]).y < 200)
{
addFish(1);
this.removeChild(MovieClip(FishOnScreen[i]));
MovieClip(FishOnScreen[i]).removeEventListener(MouseEvent.CLICK, GoToFishInfo);
FishOnScreen.splice(i, 1);
FishSpeed.splice(i,1);
}
}
//else trace("null");
}
}
public function GoToFishInfo(evt:MouseEvent):void
{
dispose();
MovieClip(root).gotoAndStop("FishInfo", "Scene 1");
var crappieinfo:CrappieInfo = new CrappieInfo();
stage.addChild(crappieinfo);
crappieinfo.x = 512;
crappieinfo.y = 384;
crappieinfo.alpha = 100;
}
public function dispose():void
{
for (var i : int = this.numChildren-1 ; i >= 0 ; i--)
{
if(this.getChildAt(i) is MovieClip)
{
this.removeChildAt(i);
MovieClip(FishOnScreen[i]).removeEventListener(Event.ADDED_TO_STAGE, Setup);
MovieClip(FishOnScreen[i]).removeEventListener(MouseEvent.CLICK, GoToFishInfo);
}
}
}
}
}
It doesn't give me any errors but it doesn't display any fish. If you could take a look at my updated code I would be grateful!
To make things better and avoid duplication of code, extend all your classes such as Crappie, Bass etc from a Base Class, call it BaseFish for example. You should create a dispose() method in this base class. That way this dispose method will be automatically available to all classes extending it. In fact, you can use this method to write common code at one place and avoid duplication.
Also, if you feel it suits the need, extend GenerateFish also from the base class, or create a similar method called dispose() in this class.
Then when you call your removeFish() method, you can call these dispose methods for your individual classes.
Create the method like this (this is just to get you started):
public function dispose():void
{
for (var i : int = this.numChildren-1 ; i >= 0 ; i--)
{
if(this.getChildAt(i) is MovieClip)
{
this.removeChildAt(i);
}
}
}
This code removes every child which is a movie clip. You may also want to remove any Event Listeners which are added in your class inside this method.
Then, move your variables genFish and genFish2 to class variables, and not declare them inside your method game()
Now in your removeFish() method do this:
public function removeFish()
{
genFish.dispose();
genFish2.dispose();
}
Follow the same logic inside your GenerateFish class to dispose all the children as they will now be instances of the same base class.
Another thing, which could be very important from a performance perspective is the ENTER_FRAME event that you are adding. Notice that this event is being added to each instance that you create inside GenerateFish. So, every instance will have its own enter frame. Maybe it will work ok in your current situation as the number of instances may be less, but this approach is not scalable, and tomorrow if you have many instances, it will certainly hinder performance.
Ideally, you should try to have only one ENTER_FRAME event listener in your main class and use the handler to change things inside your child classes.
Hope this helps you.

AS3: Class can't find another class to interact with

So I have this code inside of one of my enemy class for my flash game.
package
{
import flash.events.*;
import flash.display.*;
import flash.geom.*;
public class JumpBall extends MovieClip
{
var MTL:MovieClip = MovieClip(root);
var charMTL:MovieClip;
var bullet:Bullet = new Bullet;
public function JumpBall()
{
this.addEventListener(Event.ENTER_FRAME, EnemyBallUpdate);
}
function EnemyBallUpdate(event:Event):void
{
charMTL = MTL.char1;
var enemy:Rectangle = this.getBounds(this);
var enemy_matrix:Matrix = this.transform.matrix;
var enemyBitmap:BitmapData = new BitmapData(enemy.width, enemy.height, true, 0);
enemyBitmap.draw(this,enemy_matrix);
enemy_matrix.tx = this.x - enemy.x;
enemy_matrix.ty = this.y - enemy.y;
var char:Rectangle = charMTL.getBounds(this);
var char_matrix:Matrix = charMTL.transform.matrix;
var charBitmap:BitmapData = new BitmapData(char.width, char.height, true, 0);
charBitmap.draw(charMTL,char_matrix);
char_matrix.tx = charMTL.x - char.x;
char_matrix.ty = charMTL.y - char.y;
var enemyPoint:Point = new Point(enemy.x, enemy.y);
var charPoint:Point = new Point(char.x, char.y);
if(enemyBitmap.hitTest(enemyPoint, 0, charBitmap, charPoint, 0) && MTL.currentFrame == 2)
{
if(MTL.HP == 0)
{
MTL.RemoveListeners();
MTL.vcam_2.x = 400.2;
MTL.vcam_2.y = 224.9;
MTL.gotoAndStop(3);
MTL.HP = 3;
MTL.CC = 0;
MTL.removeChild(charMTL);
}else{
MTL.removeKeyboardEvts();
MTL.KeysOFF();
MTL.fade_mc.gotoAndPlay(2);
charMTL.gotoAndStop(1);
MTL.ySpeed = 0;
MTL.removeChild(charMTL);
}
}
enemyBitmap.dispose();
charBitmap.dispose();
}
public function removeJumpBallEL(event:Event):void
{
this.removeEventListener(Event.ENTER_FRAME, EnemyBallUpdate);
}
}
}
Upon entering frame 2 I get the silly error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at JumpBall/EnemyBallUpdate()
I can't find out why the class can't talk to the char1 MovieClip (character of my game).
I have the same type of class for a reset box with the exception that this class uses .hitTestPoint method. No errors there.
I'm trying to add my enemies to an array for interaction with a bullet class.
Here's the main timeline code:
function addJumpBall():void
{
var jumpball:JumpBall = new JumpBall;
jumpball.x = 673;
jumpball.y = 318;
addChild(jumpball);
jumpball.addEventListener(Event.REMOVED, jumpballRemoved);
JumpBallArray.push(jumpball);
}
function jumpballRemoved(event:Event):void
{
event.currentTarget.removeEventListener(Event.REMOVED, jumpballRemoved);
JumpBallArray.splice(JumpBallArray.indexOf(event.currentTarget), 1);
}
addJumpBall();
Thanks to anybody willing to help me!

how to insert sound to this code?

hello how to put sounds to this code so when tower firing bullet sound will show up together with it...i'm just nubie so i really need a help
can you help me how to put sounds in this code
this is the code
package Game
{
import flash.display.MovieClip;
import flash.events.*;
import flash.geom.*;
import Gamess.BulletThree;
import Games.BulletTwo;
public class Tower_Fire extends MovieClip
{
private var isActive:Boolean;
private var range,cooldown,damage:Number;
public function Tower_Fire()
{
isActive = false;
range = C.TOWER_FIRE_RANGE;
cooldown = C.TOWER_FIRE_COOLDOWN;
damage = C.TOWER_FIRE_DAMAGE;
this.mouseEnabled = false;
}
public function setActive()
{
isActive = true;
}
public function update()
{
if (isActive)
{
var monsters = GameController(root).monsters;
if (cooldown <= 0)
{
for (var j = 0; j < monsters.length; j++)
{
var currMonster = monsters[j];
if ((Math.pow((currMonster.x - this.x),2)
+ Math.pow((currMonster.y - this.y),2)) < this.range)
{
//spawn new bullet
var bulletRotation = (180/Math.PI)*
Math.atan2((currMonster.y - this.y),
(currMonster.x - this.x));
var newBullet = new Bullet(currMonster.x,currMonster.y,
"fire",currMonster,this.damage,bulletRotation);
newBullet.x = this.x;
newBullet.y = this.y;
GameController(root).bullets.push(newBullet);
GameController(root).mcGameStage.addChild(newBullet);
this.cooldown = C.TOWER_FIRE_COOLDOWN;
break;
}
}
}
else
{
this.cooldown -= 1;
}
}
}
}
}
Firstly, you need to export sound for AS:
and then you can play sound from code:
var sound:Sound = new Track();
sound.play();
UPDATE:
if ((Math.pow((currMonster.x - this.x),2) + Math.pow((currMonster.y - this.y),2)) < this.range)
{
//spawn new bullet
var sound:Sound = new Track();
sound.play();
var bulletRotation = (180/Math.PI)*
Math.atan2((currMonster.y - this.y), (currMonster.x - this.x));
...

ActionScript 3.0: Error #1034: Type Coercion failed: cannot convert displayObject$ to DefaultPackage at CutomeClass()

I'm a student I have a final project want to deliver it after two days.
I'm making a drag and drop game, I watched a tutorial to do that.
But after ending coding I faced a weird error!
I've I checked that my code is the same as the code in the tutorial.
This is the Debug error report:
Attempting to launch and connect to Player using URL E:\FL\ActionScript\Drag and Drop Project\DragAndDrop.swf
[SWF] E:\FL\ActionScript\Drag and Drop Project\DragAndDrop.swf - 87403 bytes after decompression
TypeError: Error #1034: Type Coercion failed: cannot convert paper1$ to DragDrop.
at Targets()[E:\FL\ActionScript\Drag and Drop Project\Targets.as:23]
My .fla File is containing 12 Objects to drag and another 12 Objects to drop on it.
The idea here is when drop the Object on the target the Object will become invisible and the target become visible (in .fla file target alpha = 0).
I made two classes:
DragDrop.as : for the objects that I'm going to drag.
Targets.as : for the targets that I'm going to drop Objects on it.
Note: match function is to animate "GameOver" MovieClip When completing the game.
DragDrop.as:
package
{
import flash.display.*;
import flash.events.*;
public class DragDrop extends Sprite
{
var origX:Number;
var origY:Number;
var target:DisplayObject;
public function DragDrop()
{
// constructor code
origX = x;
origY = y;
addEventListener(MouseEvent.MOUSE_DOWN, drag);
buttonMode = true;
}
function drag(evt:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, drop);
startDrag();
parent.addChild(this);
}
function drop(evt:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, drop);
stopDrag();
if(hitTestObject(target))
{
visible = false;
target.alpha = 1;
Object(parent).match();
}
x = origX;
y = origY;
}
}
}
Targets.as:
package
{
import flash.display.*;
import flash.events.*;
public class Targets extends MovieClip
{
var dragdrops:Array;
var numOfMatches:uint = 0;
var speed:Number = 25;
public function Targets()
{
// constructor code
dragdrops = [paper1,paper2,paper3,paper4,paper5,paper6,
paper7,paper8,paper9,paper10,paper11,paper12,];
var currentObject:DragDrop;
for(var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
currentObject.target = getChildByName(currentObject.name + "_target");
}
}
public function match():void
{
numOfMatches++;
if(numOfMatches == dragdrops.length)
{
win.addEventListener(Event.ENTER_FRAME, winGame);
}
}
function winGame(event:Event):void
{
win.y -= speed;
if(win.y <= 0)
{
win.y = 0;
win.removeEventListener(Event.ENTER_FRAME, winGame);
win.addEventListener(MouseEvent.CLICK, clickWin);
}
}
function clickWin(event:MouseEvent):void
{
win.removeEventListener(MouseEvent.CLICK, clickWin);
win.addEventListener(Event.ENTER_FRAME, animateDown);
var currentObject:DragDrop;
for(var i:uint = 0; i < dragdrops.length; i++)
{
currentObject = dragdrops[i];
getChildByName(currentObject.name + "_target").alpha = 0;
currentObject.visible = true;
}
numOfMatches = 0;
addChild(win);
}
function animateDown(event:Event):void
{
win.y += speed;
if(win.y >= stage.stageHeight)
{
win.y = stage.stageHeight;
win.removeEventListener(Event.ENTER_FRAME, animateDown);
}
}
}
}
...Thanks
Are you sure what you're putting into array in Target instance's array IS DragDrop instances?
dragdrops = [paper1,paper2,paper3,paper4,paper5,paper6,
paper7,paper8,paper9,paper10,paper11,paper12,];
I don't see any definitions for "paper1" in the code. And your error is telling paper1 is not a DragDrop instance.