Function is undefined for no apparent reason - actionscript-3

I have two event listeners calling two functions, the first checkKeyDown and then the second checkKeyUp.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.ui.Keyboard;
public class Code extends MovieClip {
var charSpeed:int = 0;
var velocity:int = 0;
var gravity:Number = 1;
var Jump:Boolean = false;
public function startGame(){
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeyUp);
}
public function Code() {
// constructor code
}
function checkKeyDown(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.LEFT){
charSpeed -= 10;
}
if (evt.keyCode == Keyboard.RIGHT){
charSpeed += 10;
}
if (evt.keyCode == Keyboard.DOWN){
if(!Jump){
velocity -= 14;
Jump = true;
}
}
function checkKeyUp(e:KeyboardEvent){
if (e.keyCode == Keyboard.LEFT){
charSpeed = 0;
}
if (e.keyCode == Keyboard.RIGHT){
charSpeed = 0;
}
}
When I first typed the code, I did the checkKeyDown function first, and when I ran it, it worked fine (without the checkKeyUp event listener of course). After this, i added the event listener and checkKeyUp function to the code, but I got an error saying "1120: Access of undefined property checkKeyUp." I have no idea why this has come up, as the checkKeyDown function works fine. If I could get some help on why I am getting this error, that would be great.

You forget a brace (char '}') at the end of checkKeyDown function.

Related

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

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! :)

Why does my shark not get damaged when colliding with other sharks?

I also get errors on my output such as:
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_AnimateHorizontally()
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_AnimateHorizontally_2()
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_EnterFrameHandler_2()[
Scene 1 - Main Menu
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
import flash.system.fscommand
import flash.events.MouseEvent
stop();
//Button Scripts
Play_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene);
function fl_ClickToGoToScene(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}
Instructions_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_10);
function fl_ClickToGoToAndStopAtFrame_10(event:MouseEvent):void
{
gotoAndStop(6);
}
function quit (event:MouseEvent):void
{
fscommand ("quit");
}
Quit_Button.addEventListener(MouseEvent.MOUSE_DOWN,quit);
Scene 2 - Game
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
import flash.system.fscommand;
import flash.events.TimerEvent;
import flash.utils.Timer;
stop();
//Variables
var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var sharkSpeed:Number = 10;
var score1:Number = 0;
var maxHP:int = 100;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;
//Health Script
function updateHealthBar():void
{
percentHP = currentHP / maxHP;
healthBar.barColor.scaleX = percentHP;
}
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_2);
function fl_ClickToGoToScene_2(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
Instructions_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextScene_2);
function fl_ClickToGoToNextScene_2(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(6, "Main Menu");
}
//Keyboard Movement
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
function keyDownHandler(KeyEvent:KeyboardEvent):void
{
if (KeyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.DOWN)
{
downPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.UP)
{
upPressed = true;
}
}
function keyUpHandler(keyEvent:KeyboardEvent):void
{
if (keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = false;
}
else if (keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = false;
}
else if (keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = false;
}
else if (keyEvent.keyCode == Keyboard.UP)
{
upPressed = false;
}
}
function gameLoop(loopEvent:Event):void
{
if (rightPressed)
{
shark.x += sharkSpeed;
}
else if (leftPressed)
{
shark.x -= sharkSpeed;
}
else if (downPressed)
{
shark.y += sharkSpeed;
}
else if (upPressed)
{
shark.y -= sharkSpeed;
}
}
//AI Movement
addEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);
function fl_AnimateHorizontally(event:Event)
{
enemy1.x += 2;
enemy2.x += 2;
enemy3.x += 2;
enemy4.x += 2;
enemy5.x += 2;
enemy6.x += 2;
megaladon.x += 2;
}
addEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally_2);
function fl_AnimateHorizontally_2(event:Event)
{
fishes.x += 1.5;
}
//Colission
function hitsTheObject(e:Event)
{
if (shark.hitTestObject(enemy1))
{
trace("player collided with enemy");
currentHP -= 50;
if (currentHP <= 0)
{
currentHP = 0;
trace("You died!");
MovieClip(this.root).gotoAndPlay(1, "Game Over");
}
updateHealthBar();
}
}
//Score Script
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler_2);
function fl_EnterFrameHandler_2(event:Event):void
{
gameScore.text = String(score1);
score1 += 1;
trace("gameScore.text is : " + gameScore.text);
trace("score1 is : " + score1);
}
//Timer Script
var myTimer:Timer = new Timer(1000,50);
myTimer.addEventListener(TimerEvent.TIMER, onTimer);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);
myTimer.start();
function onTimer(e: TimerEvent):void
{
myText_txt.text = String(myTimer.repeatCount - myTimer.currentCount);
}
function onComplete(e: TimerEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "You Survived");
}
Scene 3 - You Survived
stop();
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_4);
function fl_ClickToGoToScene_4(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
PlayAgain_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_12);
function fl_ClickToGoToScene_12(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}Scene 4 - Game Over
stop();
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_9);
function fl_ClickToGoToScene_9(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
PlayAgain_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_11);
function fl_ClickToGoToScene_11(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}
As identified in the comments, you need to remove the eventListener which you can achieve with:
removeEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);.
I would suggest implementing the following line whenever you bind to a frame event such as Event.ENTER_FRAME
this.addEventListener(Event.REMOVED_FROM_STAGE, function(){
try{
removeEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);
}catch(error){
//error handling optional in this case.
}
});
This will get called ONCE only right before the object is destroyed/removed from the stage i.e. when you call MovieClip(this.root).gotoAndPlay(1, "Game");
Note: You can just put all of your 'global' events into the try area - you don't need this call every time you add an event.
Additionally, you don't need this whatsoever for movieclips as all of your events will get cleaned up automatically once they are removed from the stage via the garbage collector.

What is the error causing my character delay its response when press a key?

I have some problems with my character's walking command. It delays its movement for a bit before it actually moves. And then at times it completely ignores the command to stop walking when I released the key.
Code:
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
hero.gotoAndStop(1);
var rightPressed: Boolean = new Boolean(false);
var leftPressed: Boolean = new Boolean(false);
var upPressed: Boolean = new Boolean(false);
var downPressed: Boolean = new Boolean(false)
var heroSpeed: Number = 10;
var keys: Array = [];
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
function keyDownHandler(KeyEvent: KeyboardEvent): void {
if (keys[Keyboard.RIGHT]) {
rightPressed = true;
} else if (keys[Keyboard.LEFT]) {
leftPressed = true;
} else if (keys[Keyboard.DOWN]) {
downPressed = true;
} else if (keys[Keyboard.UP]) {
upPressed = true;
}
}
function keyUpHandler(KeyEvent: KeyboardEvent): void {
if (keys[Keyboard.RIGHT]) {
rightPressed = false;
hero.gotoAndStop(4)
} else if (keys[Keyboard.LEFT]) {
leftPressed = false;
hero.gotoAndStop(2)
} else if (keys[Keyboard.DOWN]) {
downPressed = false;
hero.gotoAndStop(1);
} else if (keys[Keyboard.UP]) {
upPressed = false;
hero.gotoAndStop(3);
}
}
function gameLoop(loopEvent: Event): void {
if (rightPressed) {
hero.x += heroSpeed;
hero.gotoAndStop(8)
}
if (leftPressed) {
hero.x -= heroSpeed;
hero.gotoAndStop(6)
}
if (downPressed) {
hero.y += heroSpeed;
hero.gotoAndStop(5);
}
if (upPressed) {
hero.y -= heroSpeed;
hero.gotoAndStop(7);
}
}
function onKeyDown(e: KeyboardEvent): void {
keys[e.keyCode] = true;
}
function onKeyUp(e: KeyboardEvent): void {
keys[e.keyCode] = false;
}
Warnings:
Scene 1, Layer 'Actions', Frame 1, Line 68, Column 10 Warning: 1090: Migration issue: The onKeyDown event handler is not triggered automatically by Flash Player at run time in ActionScript 3.0. You must first register this handler for the event using addEventListener ( 'keyDown', callback_handler).
Scene 1, Layer 'Actions', Frame 1, Line 72, Column 10 Warning: 1090: Migration issue: The onKeyUp event handler is not triggered automatically by Flash Player at run time in ActionScript 3.0. You must first register this handler for the event using addEventListener ( 'keyUp', callback_handler).
You should get rid of the two extra KeyboardEvent handlers (onKeyUp and onKeyDown), and move the code you have there into keyUpHandler and keyDownHandler. That will solve those migration warnings (because onKeyUp and onKeyDown were special methods in AS2), and it may be the solution to your other problem: I guess sometimes the onKeyDown handler gets executed after keyDownHandler, which means the boolean values in your array are not set yet and no movement will start.
Even better: also get rid of the array with booleans (and keys! you're abusing an Array for Dictionary use) and do it like this:
function keyDownHandler(KeyEvent: KeyboardEvent): void {
if (event.keyCode==Keyboard.RIGHT]) {
rightPressed = true;
}
//etc
}

Actionscript 3.0: Cannot get key input

guys. I created a little game. Nothing actually happening thought, because im not getting my keyboard input. I spend some time trying to create my own taht didnt work. Then I copy/pasted code from official actionscript 3.0 reference page, but tweaked it for my game (but I didnt touch anything related to keyboard stuff). Also the only thing my game returns in cosnole is false
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
stop();
var left = false;
var right = false;
var speed = 0.3;
player.addEventListener(KeyboardEvent.KEY_DOWN, keydF);
player.addEventListener(KeyboardEvent.KEY_UP, keyuF);
player.addEventListener(Event.ENTER_FRAME, updF);
function keydF(event:KeyboardEvent):void {
trace("test0");
if(event.keyCode == Keyboard.D) {
trace("test1");
left = true;
}
if(event.keyCode == Keyboard.A) {
right = true;
}
}
function keyuF(event:KeyboardEvent):void {
trace("test2");
if(event.keyCode == Keyboard.D) {
left = false;
}
if(event.keyCode == Keyboard.A) {
right = false;
}
}
function updF(e:Event):void {
if(left) {
level.x -= speed;
}
if(right) {
level.x += speed;
}
trace(left + ""); //always false :\
}
If you want to get the key input to your app, you should add the listeners to the stage :)

AS3 - Buttons do not work upon reentering frame

I've set up three buttons in the first frame which are supposed to switch frames. When the program first runs, there are no errors, and i can click any of the buttons and end up where I want. However, when going back to the first frame, the buttons no longer work. The stage listener still works though. I added the "Clicked" output to check if the function was called, which it wasn't. I know I disable the buttons in the code, but only after that button is clicked, and the task is done. I should mention I don't have the code on the timeline, but on a separate document. Here is my code:
package{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.SimpleButton;
public class DocumentClass extends MovieClip
{
public var matteOppgave:Boolean = false;
public var engelskOppgave:Boolean = false;
public var flaggOppgave:Boolean = false;
public function DocumentClass()
{
stop();
btnBok.addEventListener(MouseEvent.CLICK, matte);
btnFlagg.addEventListener(MouseEvent.CLICK, flagg);
btnPc.addEventListener(MouseEvent.CLICK, engelsk);
stage.addEventListener(Event.ENTER_FRAME, sjekk);
btnBok.enabled = true;
btnPc.enabled = true;
btnFlagg.enabled = true;
function matte(evt:MouseEvent)
{
gotoAndStop(2);
frame2();
trace("Clicked");
}
function engelsk(evt:MouseEvent)
{
gotoAndStop(3);
frame3();
trace("Clicked");
}
function flagg(evt:MouseEvent)
{
gotoAndStop(4);
frame4();
trace("Clicked");
}
function sjekk(evt:Event)
{
if(matteOppgave == true && engelskOppgave == true && flaggOppgave == true)
{
gotoAndStop(5);
}
if(matteOppgave == true)
{
btnBok.alpha = 0.5;
btnBok.enabled = false;
låsEin.alpha = 0;
}
if(engelskOppgave == true)
{
btnPc.alpha = 0.5;
btnPc.enabled = false;
låsTo.alpha = 0;
}
if(flaggOppgave == true)
{
btnFlagg.alpha = 0.5;
btnFlagg.enabled = false;
låsTre.alpha = 0;
}
}
}
I got it working from a solution posted on another forum. I made the five frames i had into movieclips, and changed back and forth using addChild() and removeChild().