Skip to main content
Inspiring
October 3, 2019
Question

createjs: implement keyboard input from external script

  • October 3, 2019
  • 2 replies
  • 472 views

I'm building a createjs game in Animate.  On frame 0 I have (in part) the following...

var goLeft = false;
var goRight = false;
var KEYCODE_LEFT=37,KEYCODE_RIGHT=39

window.onkeyup = keyUpHandler;
window.onkeydown = keyDownHandler;

function keyDownHandler(e){
	if(!e){
		var e = window.event;
	}
	switch(e.keyCode){
		case KEYCODE_LEFT: goLeft = true;break;
		case KEYCODE_RIGHT: goRight = true; break;
		case KEYCODE_UP: stage.swapChildren(gate, boarder);
	}
}

function keyUpHandler(e){
	if(!e){
		var e = window.event;
	}
	switch(e.keyCode){
		case KEYCODE_LEFT: goLeft = false;break;
		case KEYCODE_RIGHT: goRight = false; break;
	}
}

createjs.Ticker.addEventListener("tick", loopclip);
function loopclip(){
    if(goLeft) // something happens;
    if(goRight)  // the opposite happens;
}

 

This works just fine.  My question is, how do I move this to an external "game" js file?  Thanks.

    This topic has been closed for replies.

    2 replies

    bhnhAuthor
    Inspiring
    October 4, 2019

    Thanks for responding.  My basic question is, how do I write a keyboard function in an external "game.js" file?  I tried "window.onkeydown" and I got an error.

    bhnhAuthor
    Inspiring
    October 10, 2019
    Found the solution. In the "game.js" class file, use document.onkeydown and document.onkeyup.
    Legend
    October 3, 2019

    Actions pane, left side, Global, Include Script.