Error #1063 with removeEventListener - actionscript-3

I'm making a game in AS3.
I've got in my main class this function :
public function tire(e:MouseEvent):void{
puzzle.removeListeners();
}
And in my Puzzle class that :
public function removeListeners():void{
var cocoUn;
var cocoDeux;
var cocoTrois;
var cocoQuatre;
var cocoCinq;
for (var i in Engine.usableItems){ // Ditto
if (Engine.usableItems[i].displayName == "COCOUN")
cocoUn = Engine.usableItems[i];
if (Engine.usableItems[i].displayName == "COCODEUX")
cocoDeux = Engine.usableItems[i];
if (Engine.usableItems[i].displayName == "COCOTROIS")
cocoTrois = Engine.usableItems[i];
if (Engine.usableItems[i].displayName == "COCOQUATRE")
cocoQuatre = Engine.usableItems[i];
if (Engine.usableItems[i].displayName == "COCOCINQ")
cocoCinq = Engine.usableItems[i];
}
cocoUn.removeEventListener(MouseEvent.CLICK, shoot, false, 0, true);
cocoDeux.removeEventListener(MouseEvent.CLICK, shootDeux, false, 0, true);
cocoTrois.removeEventListener(MouseEvent.CLICK, shootTrois, false, 0, true);
cocoQuatre.removeEventListener(MouseEvent.CLICK, shootQuatre, false, 0, true);
cocoCinq.removeEventListener(MouseEvent.CLICK, shootCinq, false, 0, true);
}
I want my 5 items to be unclickable when the function "tire" is called in my main class.
I've got an error in debug mode.
When I click on the stage, this error appear : Error #1063: Argument count mismatch on flash.events::EventDispatcher/removeEventListener(). Expected 2, got 5.
Do you know how I can correct that ?
Thank you very much,

Method removeEventListener has only three arguments:
function removeEventListener(type:String,listener:Function,useCapture:Boolean = false):void
It should be enough to ajdust your code in the following way:
cocoUn.removeEventListener(MouseEvent.CLICK, shoot);

Related

ActionScript 3 Syntax Errors

I'm new to AS3 and this site. I'm using a tutorial from http://asgamer.com/2009/as3-flash-games-for-beginners-scores-huds-and-user-interface to create my own version of shooting game. The tutorial comes with 1 enemy and 1 game level and I'm trying to add more enemies and levels.
Here's the original Engine.as coding from the tutorial:
package com.asgamer.basics1
{ import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
public class Engine extends MovieClip
{
private var numStars:int = 80;
public static var enemyList:Array = new Array();
private var ourShip:Ship;
private var scoreHUD:ScoreHUD;
public function Engine() : void
{
ourShip = new Ship(stage);
ourShip.x = stage.stageWidth / 2;
ourShip.y = stage.stageHeight / 2;
ourShip.addEventListener("hit", shipHit, false, 0, true);
stage.addChild(ourShip);
scoreHUD = new ScoreHUD(stage);
stage.addChild(scoreHUD);
for (var i:int = 0; i < numStars; i++)
{
stage.addChildAt(new Star(stage), stage.getChildIndex(ourShip));
}
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function loop(e:Event) : void
{
if (Math.floor(Math.random() * 90) == 5)
{
var enemy:Stinger = new Stinger(stage, ourShip);
enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
enemy.addEventListener("killed", enemyKilled, false, 0, true);
enemyList.push(enemy);
stage.addChild(enemy);
}
}
private function enemyKilled(e:Event)
{
scoreHUD.updateKills(1);
scoreHUD.updateScore(e.currentTarget.points);
}
private function removeEnemy(e:Event)
{
enemyList.splice(enemyList.indexOf(e.currentTarget), 1);
}
private function shipHit(e:Event)
{
scoreHUD.updateHits(1);
}
}
}
For enemies, I've created another enemy named Stinger2 and added it under the first enemy loop as below but I got error 1021 and 5000.
private function loop(e:Event) : void
{
if (Math.floor(Math.random() * 90) == 5)
{
var enemy:Stinger = new Stinger(stage, ourShip);
enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
enemy.addEventListener("killed", enemyKilled, false, 0, true);
enemyList.push(enemy);
stage.addChild(enemy);
}
}
private function loop(e:Event) : void
{
if (Math.floor(Math.random() * 90) == 5)
{
var enemy:Stinger2 = new Stinger2(stage, ourShip);
enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
enemy.addEventListener("killed", enemyKilled, false, 0, true);
enemyList.push(enemy);
stage.addChild(enemy);
}
}
For levels, I want to create 3 different levels. The first level comes with Stinger only, the second comes with Stinger2 only and the final level comes with both Stinger and Stinger2. There is also a score system from the tutorial, the below coding is from the tutorial, it controls the chance of enemy spawns:
if (Math.floor(Math.random() * 30) == 5
I tried to change it to:
if (Math.floor(Math.random() * 30) == 5 && scoreHUD(value:Number) < 10000)
so Stinger only spawns when player's score is below 10000 (level 1) but then I got a error 1084. So how do I add multiple enemies to the array and how to make these enemies spawn between specific scores?
Error 1021 means you have two functions with the same name (loop), this is not allowed for obvious reasons.
Error 5000 is sometimes ambiguous, it usually happens when you have other problems in your code.
Error 5000: The class 'myClass' must subclass 'flash.display.MovieClip' since it is linked to a library symbol of that type
You should take a look at your library in flash to make sure you have the correct base classes declared.
Error 1084 is just a simple syntax error, you are missing a ) in your if statement.

cannot convert flash.display::Stage#2a2cdf99 to flash.display.MovieClip?

So I'm creating a platform game in Actionscript 3.0, trying to call a function that spawns blocks based on an array. The code is in a 'Game' class and is directed towards a movieclip on my .fla
When it is ran I get the error:
"cannot convert flash.display::Stage#2a2cdf99 to flash.display.MovieClip."
Here's the code:
public function GameScreen(stageRef:Stage = null )
{
this.stageRef = stageRef;
btnReturn.addEventListener(MouseEvent.MOUSE_DOWN, returnMainMenu, false, 0, true);
mcMain.addEventListener(Event.ENTER_FRAME, moveChar);
this.addEventListener(Event.ENTER_FRAME, createLvl);
this.stageRef.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
this.stageRef.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
this.stageRef.addChild(blockHolder);
}
And
private function createLvl(event:Event):void
{
var lvlArray:Array = MovieClip(root)['lvlArray' +lvlCurrent];
var lvlColumns:int = Math.ceil(lvlArray.length/16);
for(var i:int = 0;i<lvlArray.length;i++){
if(lvlArray[i] == 1){
if(i/lvlColumns == int(i/lvlColumns)){
row ++;
}
var newBlock:Block = new Block();
newBlock.graphics.beginFill(0xFFFFFF);
newBlock.graphics.drawRect(0,0,50,50);
newBlock.x = (i-(row-1)*lvlColumns)*newBlock.width;
newBlock.y = (row - 1)*newBlock.height;
blockHolder.addChild(newBlock);
} else if (lvlArray[i] == 'MAIN'){
mcMain.x = (i-(row-1)*lvlColumns)*newBlock.width;
mcMain.y = (row-1)*newBlock.height;
}
}
row = 0;
}
Please help =(
Thanks!
First of all:
Turn on "permit debugging" in your publish settings. This will give you line numbers with your errors, so you can determine the exact location of your error.
Post the entire stack trace. That error by itself is not a lot to go on.
Given the error and the code you've posted, the error must be caused by your use of MovieClip(root). The root property does not always point to the main timeline in Flash, it will point to the Stage if the display object is added directly to the stage. For example:
trace(stage.addChild(new Sprite()).root) // [object Stage]
Documentation on root: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#root

random movieClips when timer is complete

I'm making a game in AS3, and I would like to add movieClips randomly on the screen when a a timer is complete.
Exemple :
something.addEventListener(TimerEvent.TIMER_COMPLETE, Finish);
function Finish(event : TimerEvent) : void {
randomly add movieClip1 or movieClip2 or movieClip3
}
How can I do that ?
Thank you very much.
EDIT
Thank your for your answer. I've tried a lot of things, but nothing really works.. I've tried :
_movieClips.push(new _classes[Math.floor(Math.random() * _classes.length)]()); // this line chooses a random index of your _classes Array which will return the Class at that index
stageRef.addChild(_movieClips[_movieClips.length-1]);
if (stageRef.getChildByName("_movieClips[0]") == null) {
trace("poubelle1");
_movieClips[0].addEventListener(MouseEvent.CLICK, removePoubelle, false, 0, true);
}else if (stageRef.getChildByName("_movieClips[1]") == null) {
trace("poubelle2");
_movieClips[1].addEventListener(MouseEvent.CLICK, removePoubelle2, false, 0, true);
}else if (stageRef.getChildByName("_movieClips[2]") == null) {
trace("poubelle3");
_movieClips[2].addEventListener(MouseEvent.CLICK, removePoubelle3, false, 0, true);
}
No errors, but I can only click if the movieClip just appears. If I'm waiting and a second one appears, I can't click on either one of them.
I've tried :
_movieClips.push(new _classes[Math.floor(Math.random() * _classes.length)]()); // this line chooses a random index of your _classes Array which will return the Class at that index
stageRef.addChild(_movieClips[_movieClips.length-1]);
if (_movieClips[0].visible== true){
trace("poubelle1");
_movieClips[0].addEventListener(MouseEvent.CLICK, removePoubelle, false, 0, true);
}
if (_movieClips[1].visible== true){
trace("poubelle2");
_movieClips[1].addEventListener(MouseEvent.CLICK, removePoubelle2, false, 0, true);
}
if (_movieClips[2].visible== true){
trace("poubelle3");
_movieClips[2].addEventListener(MouseEvent.CLICK, removePoubelle3, false, 0, true);
}
But Error #1010: A term is undefined and has no properties.
Do you know how I can do that ?
Thanks !
You COULD use an Array 'loaded' with Class names:
var _classes:Array = new Array(movieClip1, movieClip2, movieClip3);
var _movieClips:Array = new Array(); // this Array is used to instantiate your random MovieClips
Then, in your timer finished handler:
_movieClips.push(new _classes[Math.floor(Math.random() * _classes.length)]); // this line chooses a random index of your _classes Array which will return the Class at that index
addChild(_movieClips[_movieClips.length-1]);

dropTarget showing error

I'm, creating a simple drag and drop game in flash cs 5.5. There will be several movieclip on the stage suffled. What the user need to do is drag it to another movieclip and the movieclip will switch and check if it is in right place. I used the code something like this
if (evt.target.dropTarget != null && evt.target.dropTarget.parent.name == "num1" || "num2" || "num3" || ......and so on)
{
//do your thing
}
else
{
//go back to original place
}
In above code num1, num2 and so on are name of the moveiclips. There are also other movieclips on the stage. They are backgrounds. This works fine if I drag and dropped the movieclip(let say num1) on other movieclips(let say num2) as expected. But when I droped it on other movieclip(background), it shows error. I traced evt.target.dropTarget.parent.name inside the if condition and it shows the name of other movieclip(background). Why it is showing the name of the other movieclip(background) when the condition hasn't met which is the name isn't num1 or num2 or so on...? Can someone tell me if I'm doing anything wrong ? or is there another way to do this ?
Don't know if you're posting pseudo-code or not, but this won't work as a condition:
evt.target.dropTarget.parent.name == "num1" || "num2" || "num3" ||
This will always return true because it's evaluating the string "num2" as a condition. Look at the Boolean function for more information.
What you want is something like:
var par_name = evt.target.dropTarget.parent.name;
if (evt.target.dropTarget != null && par_name == "num1" || par_name=="num2" || par_name=="num3" )
or you can streamline this in many ways-- e.g.:
var valid_targets = ["num1","num2","num3"];
if ( evt.target.dropTarget != null && (valid_targets.indexOf(par_name)>=0) )
hope this simple and dummy example will be possible to explain a little bit more how to implement this logic. (of course, it's just a draft, but can be used as mockup)
Try something like:
//your package name (I just created a simple example, you should refactor and add your logic
package nu.gpeart.TheGunnersExample.components
{
import flash.geom.Rectangle;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;
/**
* #file DraggableItem.as
* #created Dec 18, 2013 - 9:02:52 AM
*/
public class DraggableItem extends Sprite
{
private var _item:Sprite;
private var _rightPlace:Point;
private var _dropTarget:Sprite;
private var _originalPlace:Point;
public function DraggableItem(parent:Sprite,
viewport:Rectangle,
color:uint,
rightPlace:Point,
dropTarget:Sprite)
{
_originalPlace = new Point(viewport.x, viewport.y);
_rightPlace = rightPlace;
_dropTarget = dropTarget;
_item = new Sprite();
_item.graphics.beginFill(color);
_item.graphics.drawRect(0, 0, viewport.width, viewport.height);
_item.graphics.endFill();
parent.addChild(_item);
addMouseDownListener();
}
private function addMouseDownListener():void
{
_item.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false, 0, true);
}
private function mouseDownHandler(event:MouseEvent):void
{
_item.startDrag();
removeMouseDownListener();
addMouseUpListeners();
}
private function addMouseUpListeners():void
{
_item.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, false, 0, true);
_item.parent.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, false, 0, true);
}
private function mouseUpHandler(event:MouseEvent):void
{
_item.stopDrag();
removeMouseUpListeners();
addMouseDownListener();
startLogic();
}
private function startLogic():void
{
if (_item.hitTestObject(_dropTarget))
{
(_item.hitTestPoint(_rightPlace.x, _rightPlace.y)) ? rightPositionLogic() : wrongPositionLogic();
}
else
{
wrongPositionLogic();
}
}
private function wrongPositionLogic():void
{
_item.x = _originalPlace.x;
_item.y = _originalPlace.y;
// go back to original place
}
private function rightPositionLogic():void
{
trace('dropped the right place');
// do your thing
}
private function removeMouseUpListeners():void
{
_item.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
_item.parent.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
}
private function removeMouseDownListener():void
{
_item.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
}
}
And to use, you just need something like:
var rightPlace:Point = new Point(461, 554);
var originalPosition:Point = new Point(50, 50);
var itemWidth:Number = 50;
var itemHeight:Number = 50;
var viewport:Rectangle = new Rectangle(originalPosition.x, originalPosition.y, itemWidth, itemHeight);
var itemColor:uint = 0xf67821;
//container (the Sprite where are you adding all your objects
//dropTarget (the Sprite you want to detect the hitTest
var draggableItem:DraggableItem = new DraggableItem(container, viewport, itemColor, rightPlace, dropTarget);

Getting a size from a loaded file via a File variable type ActionScript3

Cannot get my file size! I have a variable that loads the file, and then on my fileCompleteLoad event i want to check the size of that file (.png).
// clickButton event to load the file
public function onMouseClick(e:MouseEvent):void{
_fileRef = new File();
_fileRef.addEventListener(Event.SELECT, onFileSelected, false, 0, true);
_fileRef.addEventListener(Event.CANCEL, onCancel, false, 0, true);
_fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
_fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
onSecurityError, false, 0, true);
_fileRef.browse([_imageFilter]);
}
// selected event
public function onFileSelected(evt:Event):void
{
_fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress, false, 0, true);
_fileRef.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
_fileRef.load();
}
// thats my eventComplete
public function onComplete(evt:Event):void
{
_msgSuccessErrorTextField.text = "File was successfully loaded.";
_pngInputTextField.text = String(_fileRef.nativePath);
_atfOutputTextField.text = _fileRef.nativePath.replace(".png",".atf");
_inputNativeProcess = _fileRef.nativePath;
_outputNativeProcess = _atfOutputTextField.text;
_flagLoadedFile = new Boolean(true);
var test:Bitmap = evt.target.data as Bitmap;
if(test){
trace(test.height);
}
_fileRef.removeEventListener(Event.SELECT, onFileSelected);
_fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress);
_fileRef.removeEventListener(Event.COMPLETE, onComplete);
_fileRef.removeEventListener(Event.CANCEL, onCancel);
Now, in that event i want to check my file size... I ve tried many things but didnt get success... and sometimes i get null from my _fileRef.data.
Any suggestions to solve that?
thx
Just to make sure, are you getting the data inside the onComplete handler? The code you show doesn't do that right now. Should be something like :
_fileRef.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
private function onComplete(e:Event):void
{
var test:Bitmap = e.target.data as Bitmap;
if(test)
trace(test.height);
}
the Answer is -
//add that on my public function onComplete(evt:Event):void{}
var loader:Loader = new Loader();
loader.loadBytes(byteArray);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);
// build another event
publicfunction loaderComplete(event:Event):void
{
var loaderInfo:LoaderInfo = LoaderInfo(event.target);
var bitmapData:BitmapData = new BitmapData(loaderInfo.width,
loaderInfo.height, false, 0xFFFFFF);
bitmapData.draw(loaderInfo.loader);
// result: bitmapData
}
now i can get the Heigh, witdh and whatever... thx!