Book Image

haXe 2 Beginner's Guide

5 (1)
Book Image

haXe 2 Beginner's Guide

5 (1)

Overview of this book

Table of Contents (21 chapters)
haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – Handling moves


Now, we will add a function that allows the user to control his character.

To do so, we need to listen for when a key is pressed to set the speed of the character, and for when a key is depressed in order to set the speed to 0.

We will also store the speed as a static variable:

class Game
{
   static var player : Guy;
   static var horizontalSpeed : Int = 0;

   public static function main(): Void
   {
      player = new Guy();
      //Add it to the stage
      flash.Lib.current.stage.addChild(player);

      //Place it at the good place on stage.
      player.x = 200;
      player.y = 300;
      player.width=50;
      player.height = 100;
      
      flash.Lib.current.stage.addEventListener(flash.events.KeyboardEvent.KEY_DOWN, keyDown);
      flash.Lib.current.stage.addEventListener(flash.events.KeyboardEvent.KEY_UP, keyUp);
   }
   
   private static function keyDown(args : flash.events.KeyboardEvent)
   {
      trace(args.keyCode);
      switch(args.keyCode...