Jack
Jack

Reputation: 400

AS3: Key Press clicks the tower

I am almost done with an Engineering Internship where a group and I were assigned a project involving hardware and programming. Our project was an old-style arcade box Tower Defense Game with a theme of Stopping Global Warming.

After following a nicely made tutorial, we have completed our game except for one thing: in the tutorial's game you select a tower by clicking a button with the mouse, however for our purposes we need it so the user presses a keyboard button to select the tower (we already got it so when you press a button on the arcade box and it presses a key).

Below is the code section that I believe contains the code that needs to be changed. I have tried fiddling with KeyboardEvent.KEY_DOWN, however to no avail.

In case everything above made no sense, I need to make the event listener listen for the "w" key to be pressed, and then select the Fire Tower.

setupGame();

// Initialise the UI event listeners.
mcGameUI.btnBuildFireTower.addEventListener(KeyboardEvent.KEY_DOWN, clickTowerFire);
mcGameUI.btnBuildFireTower.addEventListener(MouseEvent.ROLL_OVER, showTowerFireHelp);
mcGameUI.btnBuildFireTower.addEventListener(MouseEvent.ROLL_OUT, clearHelp);

Thank you!!!!

Upvotes: 1

Views: 51

Answers (1)

Marty
Marty

Reputation: 39466

Keyboard events need to be listened for on an object which has focus. Fortunately, the stage always has focus, so it's a good idea to attach your keyboard event listeners there, e.g.

stage.addEventListener(KeyboardEvent.KEY_DOWN, clickTowerFire);

If you want to add actions based on a specific key press, you can use the keyCode property that is attached to the KeyboardEvent:

function clickTowerFire(event:KeyboardEvent):void
{
    if(event.keyCode === 87) // W
    {
        // Your existing code here.
    }
}

Upvotes: 1

Related Questions