Reputation: 27
I'm trying to make a game, but my character is allowed to move on the title screen (if I use the keys to move him, and then press "Play
", the character will already be moved to a different location.) I thought that I should create a variable called "CanMove
", set it to false, and eventually set it to true when I press the "Play
" button. However, I don't know what I'm doing wrong. I put this code all the way at the end of the document (but still in the $(document).ready
part):
if (canMove === true) {
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
case 65: //if LEFT direction pressed down:
walkLeft();
break;
case 83: //if DOWN direction pressed down:
$('#character').animate({top: "+=18px"}, 0.1);
rightCharacter()
changeRightCharacter();
break;
case 87: //if UP direction pressed down:
jumpUp();
break;
case 68: //if RIGHT direction pressed down:
walkRight();
break;
default:
break;
}
});
}
You see, I set canMove to true when I press the button (the code for the button is above the code I pasted here, though), yet it still won't work. I think it is because the document already checks if canMove is true or false once it loads, and it doesn't make a difference if you set it to true or false after it loads. I don't know how to change that, so I'd appreciate any help!
PS: I would also like the ability to prevent the character from moving later in the game (i.e. during textboxes, etc.)
Upvotes: 0
Views: 68
Reputation: 198476
Put the if
inside the keydown
handler. This way, the document will detect keys always, but only respond to them if canMove
is set.
Regarding "I don't know what I'm doing wrong"... yes, you do, you describe it perfectly in your paragraph below the code: you test canMove
only once at the start, and decide whether to set a keydown
handler or not depending on that. If you don't set it, the document won't listen for keydowns ever again (unless you're also setting it from somewhere else in the code); if you do, then it will listen for keydowns forever (unless you are removing the handler somewhere else in the code).
Upvotes: 2