Game Tutorial 2


  • Create a player object and move it by keyboard input.
  • Learn how to check keyboard inputs using TMI.keyboard(an instance of TM.InputManager_Keyboard)
  • Learn how to find keyboard key codes.
  • Learn how to loop codes using window.setInterval function.


**View soruce code: game-tutorial2.js

I will only explain the code that is new or updated from the previous tutorial.

var KEYSET = {
  LEFT: 37,
  UP: 38,
  RIGHT: 39,
  DOWN: 40,

These are the the key codes for arrow keys that will be used in this program.

You can get key codes for keyboard in the following steps.

  1. Run Text Game Maker JS Starter Program(double click index.html).
  2. Open the browser console.
  3. Click Screen.
  4. Press keys on your keyboard.
  5. The key codes are logged in the browser console.

**key codes are logged in the browser console if true is passed to TM.InputManager's constructor as the second parameter. in this example code, debugSetting.devMode is passed which is true.

var player = {
  x: 22,
  y: 10,
  text: "[-<>-]",

player object has x, y positions and text. I set the first x, y positions as (22,10).

function calculate(){
  // check key and move player
  if(TMI.keyboard.checkKey(KEYSET.LEFT) && player.x>2) player.x--;
  if(TMI.keyboard.checkKey(KEYSET.UP) && player.y>1) player.y--;
  if(TMI.keyboard.checkKey(KEYSET.RIGHT) && player.x+player.text.length<frame.width-2) player.x++;
  if(TMI.keyboard.checkKey(KEYSET.DOWN) && player.y<frame.height-2) player.y++;

calculate functions is created. It checks key input and updates player object.
Key inputs can check using TMI.keyboard.checkKey function in loop. (TMI.keyboard is an instance of TM.InputManager_keyboard.)

function draw(){

  //draw score
  TMS.insertTextAt(frame.x,frame.y-1,"Score: ");

  //draw frame
  for(var i=0; i<frame.height; i++){
    for(var j=0; j<frame.width; j++){
      if((i===0 || i==frame.height-1 || j===0 || j==frame.width-2)&&(j%2 === 0)){

  //draw player

Code added to draw player under //draw player.

var mainInterval = window.setInterval(function(){

Loop calculate and draw functions using window.setInterva function. window.setInterval function is from window object in Javascript, not from Text Game Maker JS. It is used like window.setInterval(function_to_loop, interval_time), interval_time is milliseconds. Therefore it check key input and update Screen every 0.03 seconds.

Run Example

Press arrow keys in your keyboard to move the player after clicking Screen. also you can see key codes are logged on the browser console.

Change the keys to a,w,s,d as practice before you move to the next chapter.


Add Comment

Login with SNS account to write comments. see details