Jump to content

Issues with Input


Recommended Posts

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;}
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...