GravityGamesInteractive Posted December 30, 2014 Share Posted December 30, 2014 Hello, I've been having a few issues with input on my HTML5 game. I've tested that the boolean variables leftPressed and rightPressed are being set correctly, and they are, but when I try to access them outside of the Game Object, I get moot, not even an undefined error. I think I'm always getting false, but I'm not sure. Here's the relevant code: Game Object:var Game = function() { ...document.addEventListener('keydown', function(event) { if (event.keyCode == 37) { leftPressed=true; } else if (event.keyCode == 39) { rightPressed=true; }});document.addEventListener('keyup', function(event) { if(event.keyCode == 37) { leftPressed=false; } else if(event.keyCode == 39) { rightPressed=false; }}); ...Other Object:if(this.game.leftPressed){ this.x-=2;}if(this.game.rightPressed){ this.x+=2;} Quote Link to comment Share on other sites More sharing options...
EmployeeNumber8 Posted January 6, 2015 Share Posted January 6, 2015 You missed the "this" keyword when you assign to leftPressed and rightPressed I'm going to assume it was just a typo. We've all done it haha. Quote Link to comment Share on other sites More sharing options...
ericjbasti Posted January 8, 2015 Share Posted January 8, 2015 Actually it more than just a 'this'. In that context 'this' is referring to the document. Since it looks like you have a global object of Game, well use that: document.addEventListener('keydown', function(event) { if (event.keyCode == 37) { Game.leftPressed=true; } else if (event.keyCode == 39) { Game.rightPressed=true; }});document.addEventListener('keyup', function(event) { if(event.keyCode == 37) { Game.leftPressed=false; } else if(event.keyCode == 39) { Game.rightPressed=false; }});if(Game.leftPressed){ this.x-=2;}if(Game.rightPressed){ this.x+=2;}This can probably be cleaned up a bit... but based on the code provided this should work. GravityGamesInteractive 1 Quote Link to comment Share on other sites More sharing options...
GravityGamesInteractive Posted January 8, 2015 Author Share Posted January 8, 2015 Thanks ericjbasti, that seemed to work! Now I can stop passing in so many input related booleans to the update loop. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.