HTML and CSS Reference
In-Depth Information
You will use these direction points to help with collision detection later on in this section. For now, you need to
start setting up your Input class and working with JavaScript's input events in TypeScript. Create the following class:
export class Input {
From here, you set up the basic constructor and add a listener for the keyboard events within it:
constructor (){
window.addEventListener("keyup", event => this.keyup(event) , false);
Again, you can see that the TypeScript arrow notation is being used to define the event callback. You add the
listener and then bind the returned event to your keyup method, which you will create next:
keyup( event: Event ):void {
var keyCode = event["keyCode"];
switch (keyCode){
case Keyboard.UP:
this.newDirection = Directions.UP;
case Keyboard.RIGHT:
this.newDirection = Directions.RIGHT;
case Keyboard.DOWN:
this.newDirection = Directions.DOWN;
case Keyboard.LEFT:
this.newDirection = Directions.LEFT;
There is a lot in this method, but it's pretty straightforward stuff. You stop the event from propagating and then do
a switch on the event keyCode . Because you typed the event to Event , you can attempt to access its properties directly,
just like you do in JavaScript. There is one problem, however: TypeScript's compiler doesn't recognize keyCode as
part of the event type. To get around this, you access the property in array notation, which bypasses the compiler's
type-checking system and lets you still access the property on the object and not get an error. This is a neat trick if you
run into type issues and don't have the time or the know-how to fix them. The rest of the switch statement assigns the
direction point to a property called newDirection . Add this to your class, above the constructor:
newDirection: geom.Point;
Finally, you just need to create your clear method, which will allow you to reset the Input class on each frame by
adding the following code to the end of the class:
clear():void {
this.newDirection = null;
Search WWH ::

Custom Search