**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.
**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(){ //clearScreen TMS.clearScreen(); //draw score TMS.insertTextAt(frame.x,frame.y-1,"Score: "); TMS.insertText(frame.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)){ TMS.insertTextAt(frame.x+j,frame.y+i,"■"); } } } //draw player TMS.insertTextAt(frame.x+player.x,frame.y+player.y,player.text); }
Code added to draw player under //draw player.
var mainInterval = window.setInterval(function(){ calculate(); draw(); },30);
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.
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.
Comments
Login with SNS account to write comments. see details