I have three classes that I am using and have shortened for ease of reading, leaving out the package and imports. MainClass is my document class, Player is a class linked to a movieclip, and KeyHandler is a class i’m using to contain the functions for my key presses. First, the code..
public class TestMain extends Sprite
{
public var keyHandler:KeyHandler = new KeyHandler();
public var timer:Timer = new Timer(30);
public var player:Player = new Player();
public function TestMain()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler.KeyPress);
stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler.KeyRelease);
timer.addEventListener(TimerEvent.TIMER, onTick);
timer.start();
stage.addChild(player);
}
public function onTick(timerEvent:TimerEvent)
{
player.Move();
}
}
Player Class..
public class Player extends Sprite
{
public var keyHandler:KeyHandler = new KeyHandler();
public function Player()
{
}
public function Move():void
{
trace("this works");
if (keyHandler.upKeyIsPressed)
{
trace("this doesnt work")
}
}
}
KeyHandler class..
public class KeyHandler extends Sprite
{
public var upKeyIsPressed:Boolean = false;
public function KeyHandler()
{
}
public function KeyPress(keyboardEvent:KeyboardEvent)
{
if (keyboardEvent.keyCode == Keyboard.UP)
{
upKeyIsPressed = true;
}
}
public function KeyRelease(keyboardEvent:KeyboardEvent)
{
if (keyboardEvent.keyCode == Keyboard.UP)
{
upKeyIsPressed = false;
}
}
}
Holding down the up key doesn’t trace anything, but the Move function does. Should I make KeyHandler static, or is there an easy fix? Is this bad practice to do?
This is option 1 from my comment
TestMain
Player
KeyHandler
Option 2 is making a “Singleton” type of setup where you get an instance of the class through a static method. Only one instance of the class is used throughout in this case and doesn’t require passing the instance through objects that don’t actually need a handle on it themselves. In the link in my comment on the OP I there’s discussion on options for enforcing the pattern so no new instances are accidentally made, I’m just using the simple option here that causes a runtime error:
Player
TestMain
Here’s another way to enforce the Singleton that will cause compile time errors so you see the problem earlier on:
http://blog.pixelbreaker.com/actionscript-3-0/as30-better-singletons