HTML and CSS Reference
In-Depth Information
Before moving on, note that you didn't add an Input interface to help cut down on the amount of code you have
here. This interface could easily be added, allowing you to support a mouse, touch screen, or joystick down the road.
You can simply create a common interface for input in your game and classes for each type and then, at runtime, swap
them out, based on the user's device or preferred input. Always think of how to take advantage of TypeScript's language,
such as interfaces and support for typing, which you may not be used to in traditional JavaScript development.
At this point, you can begin to integrate this interface into your game class. Switch back to the game.ts file, and
add the following property to your game class:
input: input.Input;
Now, you need to add the following code to your constructor, before the map data:
this.input = new input.Input();
In your update method, you want to check if the newDirection property was set. Add this before you test for the
invalid flag and draw call:
if (this.input.newDirection) {
As you can see, the Input class is polled for its newDirection . From here, you make a call to a move method and
pass in the value. Then, you clear the input for the next frame so that the player needs to press and release the arrow
key in order to move. Add the following method to your game class:
move(newDirection:geom.Point): void {
var tmpPoint: geom.Point = this.playerPosition.clone();
tmpPoint.x += newDirection.x;
tmpPoint.y += newDirection.y;
var tile: string =;
switch (tile) {
case " ":
this.playerPosition = tmpPoint;
this.invalid = true;
This will represent the core of your collision detection. It's actually really simple. You clone the player's current
position and then add the newDirection x, y values to it. From here, you can preview the next tile the player is going
to enter by getting it from the map via its getTileType method. This is another reason it was important to abstract the
tile array data inside the map class and expose an easier way to access individual tiles. Once you have the next tile, you
simply see if it's empty via a switch. If so, you set the current player's position to the temporary point and invalidate
the display. The game loop will automatically update the display on the next frame. Run the game, and you should be
able to move around now, as illustrated in Figure 19-17 .
Search WWH ::

Custom Search