Add pause key in a game javascript - javascript

I create little game but I have some trouble to put a pause key. It doesn't work. Can you see what is wrong and correct me? Thanks. I would like to know how to implement a pause key and a key for restart for not refresh the page for do it.
Link of the game
code:
//this is where the keybinding occurs
$(document).keydown(function(e){
if(!gameOver && !playerHit){
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
}
Keys down:
switch(e.keyCode){
case 75: //this is shoot (k)
//shoot missile here
var playerposx = $("#player").x();
var playerposy = $("#player").y();
var name = "playerMissle_"+Math.ceil(Math.random()*1000);
$("#playerMissileLayer").addSprite(name,{animation: missile["player"], posx: playerposx + 90, posy: playerposy + 14, width: 36,height: 10});
$("#"+name).addClass("playerMissiles")
break;
case 65: //this is left! (a)
$("#playerBooster").setAnimation();
break;
case 87: //this is up! (w)
$("#playerBoostUp").setAnimation(playerAnimation["up"]);
break;
case 68: //this is right (d)
$("#playerBooster").setAnimation(playerAnimation["booster"]);
break;
case 83: //this is down! (s)
$("#playerBoostDown").setAnimation(playerAnimation["down"]);
break;
Pause key P:
case 80: //pause (p)
pauseGame();
alert ("paused")
}
}
});
Key released:
//this is where the keybinding occurs
$(document).keyup(function(e){
if(!gameOver && !playerHit){
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
switch(e.keyCode){
case 65: //this is left! (a)
$("#playerBooster").setAnimation(playerAnimation["boost"]);
break;
case 87: //this is up! (w)
$("#playerBoostUp").setAnimation();
break;
case 68: //this is right (d)
$("#playerBooster").setAnimation(playerAnimation["boost"]);
break;
case 83: //this is down! (s)
$("#playerBoostDown").setAnimation();
break;
case 80: //pause (p)
pauseGame();
}
}
});
Pause function:
function Pause () {
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
}};

Try and check if the P key is registered at all (using alert or a console message).
Then
I would also suggest the following: do not set the actual gameloop interval (or call game functions) inside the keyUp / keyDown handlers. Place actual game code inside their own functions, for example:
bGamePaused = false;
// key handlers
$(document).keydown(function(e){
switch(e.keyCode){
case 80:
// check if the key is registered
console.log("p is pressed, pause the game!");
// toggle the paused status:
bGamePaused = !bGamePaused;
// tell gameQuery to pause or resume the game
(bGamePaused) ? pauseGame() : resumeGame();
break;
}
$(document).keyup(function(e){
switch(e.keyCode){
// do not check for pause here. you only need to check when the key is either pressed or released, or the function will get called twice.
}

Related

js move object with arrow keys (only once)

Hi I've taken the code (to move objects with arrow keys) from some internet template. Since then, I've limited the area that the object can be moving around but I still have a problem that when I press an arrow key the object moves more than necessary, I just want to move it 20px in the appropriate direction, regardless how long the key is pressed.
Here are the functions:
var GameInput = (function() {
var pressedKeys = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
// Convert ASCII codes to letters
key = String.fromCharCode(event.keyCode);
}
pressedKeys[key] = status;
}
document.addEventListener('keydown', function(e) {
setKey(e, true);
});
document.addEventListener('keyup', function(e) {
setKey(e, false);
});
function isDown(key) {
return pressedKeys[key];
}
return {
isDown: isDown
};
})();
And the function calling it:
function update() {
if(GameInput.isDown('DOWN')) {
if(player.y < canvas.height - player.sizeY) {
player.y += 20;
}
}
if(GameInput.isDown('UP')) {
if(player.y > 0) {
player.y -= 20;
}
}
if(GameInput.isDown('LEFT')) {
if(player.x > 0) {
player.x -= 20;
}
}
if(GameInput.isDown('RIGHT')) {
// Don't go out of canvas
if(player.x < canvas.width - player.sizeX) {
player.x += 20;
}
}
// You can pass any letter to `isDown`, in addition to DOWN,
// UP, LEFT, RIGHT, and SPACE:
// if(GameInput.isDown('a')) { ... }
}
I understand why it does what it does but I have not been able to modify it to only move 20px regardless how much time a key is pressed.
Thank you
How about using the keyup event to allow the operation to repeat only when a new key is pressed. Something like:
var allowRepeat = true;
document.addEventListener('keydown', function(e) {
if (allowRepeat) {
setKey(e, true);
}
allowRepeat = false;
});
document.addEventListener('keyup', function(e) {
allowRepeat = true;
setKey(e, false);
});
I think your logic is a little reverted, what you want is to disallow update 'before key up is fired', from your code, as long as the keyUp event is not fired, isDown('XXX') is still true..
So this is what you need: (you should do some refactoring, but this should work)
var GameInput = (function() {
....
var _allowUpdate = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
// Convert ASCII codes to letters
key = String.fromCharCode(event.keyCode);
}
// This checks whether it's the first time the key being pressed.
allowUpdate[key] = !pressedKeys[key] && status;
pressedKeys[key] = status;
}
function allowUpdate(key) {
_allowUpdate[key] ;
}
return {
allowUpdate: allowUpdate
};
}
function update() {
if(GameInput.allowUpdate('DOWN')) {
if(player.y < canvas.height - player.sizeY) {
player.y += 20;
}
}
.....
}

How to Javascript/html5 Input Keyboard in-order set (not in the same time)

I have create a simple game that need to press keyboard buttons exactly follow the step in order to move character. But I cannot figure out how to do it and all I found on the internet is about pressing multiple keyboard buttons in the same time. (set array and use &&)
Picture this: you have to press A then, B, C, and D to move character forward, or D,C,B,andA in-order to move back. All of these are not press at the same time, but follow the set.
So can someone tell me or give me some clue how to do that? Also, what about pressing button like double click mouse?- is it possible.
Thanks in advance.
Just something off the top of my head:
var aPressed = false;
var bPressed = false;
var cPressed = false;
var dPressed = false;
document.onkeydown = function (event) {
var key = event.keyCode;
switch (key) {
case 65:
aPressed = true;
break;
case 66:
if (aPressed) {
bPressed = true;
}
break;
case 67:
if (aPressed && bPressed) {
cPressed = true;
}
break;
case 68:
if (aPressed && bPressed && cPressed) {
dPressed = true;
}
break;
default: //Reset all buttons
aPressed = false;
bPressed = false;
cPressed = false;
dPressed = false;
break;
}
if (dPressed) {
//Move forward and reset pressed buttons
}
}
Hope this can help you a bit :)
EDIT:
as for the "double pressing" a button, you could combine it with something like this:
var presscount = 0;
var delay = 300;
document.onkeydown = function(){
presscount++;
if(presscount == 1)
{
setTimeout(function(){
if(presscount == 1)
{
//stuff to do on single press
}
else
{
//stuff to do on double press
}
}, delay);
}
}

How do I best combine directional movements (up and left, up and right...) when moving objects?

I am using EaselJS in Javascript and I am using the keydown and keyup events to catch keyboard input (see below):
/*Connecting keydown input to keyPressed handler*/
this.document.onkeydown = keyPressed;
/*Connecting key up event to keyUp handler*/
this.document.onkeyup = keyUp;
And I have the following code to capture when up down, left and/or right are pressed, and to react to them temporarily. The movement is very shabby now, and I'm still trying to refine it. For me to be able to move my object correctly, I should be able to catch angle changes (left/right) and acceleration (forward) simulataneously.
Here is the keyDown code I have currently:
/*Keyboard input handlers - keydown and keyup*/
function keyPressed(event){
if(!event){ var event = window.event; }
switch(event.keyCode){
case KEYCODE_LEFT:
console.log("left held");
ellip.x -= 5;
break;
case KEYCODE_RIGHT:
console.log("right held");
ellip.x += 5;
break;
case KEYCODE_UP:
console.log("up held");
ellip.y -= 5;
break;
case KEYCODE_DOWN:
console.log("down held");
ellip.y += 5;
break;
}
}
Now notice in the console that hitting two of the arrow buttons does not yield combinations of messages (eg. up held and right held)
How do I go about dealing (or listening) to multiple events?
Here is a Fiddle! use the up, down, left and right arrows to move the red blotch around.
The way to handle this would be to capture which keys are down in your keyDown code and then do the movement itself in the handleTick function. You'll need to look at keyUp too so you know when the key is no longer down:
/*Keyboard input handlers - keydown and keyup*/
var left,
right,
up,
down;
function keyPressed(event){
if(!event){ var event = window.event; }
switch(event.keyCode){
case KEYCODE_LEFT:
console.log("left held");
left = true;
break;
case KEYCODE_RIGHT:
console.log("right held");
right = true;
break;
case KEYCODE_UP:
console.log("up held");
up = true;
break;
case KEYCODE_DOWN:
console.log("down held");
down = true;
break;
}
}
function keyReleased(event){
if(!event){ var event = window.event; }
switch(event.keyCode){
case KEYCODE_LEFT:
console.log("left released");
left = false;
break;
case KEYCODE_RIGHT:
console.log("right released");
right = false;
break;
case KEYCODE_UP:
console.log("up released");
up = false;
break;
case KEYCODE_DOWN:
console.log("down released");
down = false;
break;
}
}
function handleTick(event){
/*Scaling down the image*/
ellip.scaleX = 0.10;
ellip.scaleY = 0.10;
if(left) {
ellip.x -= 5;
} else if(right) {
ellip.x += 5;
}
if(up) {
ellip.y -= 5;
} else if(down) {
ellip.y += 5;
}
if (ellip.x > stage.canvas.width) {
ellip.x = stage.canvas.width;
}
stage.update();
}
EDIT: forked fiddle with this in action: http://jsfiddle.net/t2M82/

JQuery while keydown

How can i make a movement of a element while the user is "keydown" and then if he make "keyup" to stop the animation(movement), this is my code by now
$(document).ready(function(){
function checkKey(e){
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keydown (checkKey);
} else {
$(document).keydown (checkKey);
}
})
i want to move the cube while the user press the key (down, left, up, right), not with every press, is possible?
You need a simple 2D engine that will setup a game loop.
Simple demo: http://jsfiddle.net/kzXek/
Source: https://github.com/superrob/simple-2D-javascript-engine/blob/master/simple2d.html
Is that you are looking for?
$(document).on("keyup", function() {
$("#cube").stop(true);
});
DEMO: http://jsfiddle.net/LjGRe/
you can just change the checkKey function, and add this to it :
function checkKey(e){
$(document).keyup(return);
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
I think using a timer to handle the animation is better.
You just start the timer when a key is pressed and stop it when the key is released ..
Here is a simple solution that handles multiple keypresses (can move diagonally)
var direction = {top:0,left:0},
animator = null,
cube = $("#cube");
function animate(){
cube.css({
top: '+=' + direction.top,
left: '+=' + direction.left
});
}
function setProperties(keyCode, unset){
switch (keyCode) {
case 40:
direction.top = (unset)?0:2;
break;
case 38:
direction.top = (unset)?0:-2;
break;
case 37:
direction.left = (unset)?0:-2;
break;
case 39:
direction.left = (unset)?0:2;
break;
}
}
function setKey(e) {
setProperties(e.keyCode);
if (animator === null){
animator = setInterval(animate, 10);
}
}
function unsetKey(e){
setProperties(e.keyCode, true);
if (direction.top === 0 && direction.left === 0){
clearTimeout(animator);
animator = null;
}
}
$(document)
.on("keyup", unsetKey)
.on('keydown', setKey);
Demo at http://jsfiddle.net/gaby/Cu6nW/

JavaScript Keyboard Event Not Firing

For some very odd reason when you press keys in the order of forward, spacebar, and left. Left does not fire and returns spacebar instead. Any other combination of three keys works perfectly fine, but not that one. Any clues as to why?
var Ctrl = {
init: function() {
window.addEventListener('keydown', this.keyDown, true);
window.addEventListener('keyup', this.keyUp, true);
},
keyDown: function(event) {
console.log(event.keyCode);
switch(event.keyCode) {
case 37: // Left
Ctrl.left = true;
break;
case 39: // Right
Ctrl.right = true;
break;
case 38: // up
Ctrl.up = true;
break;
case 40: // down
Ctrl.down = true;
break;
case 32:
Ctrl.space = true;
break;
default:
break;
}
},
keyUp: function(event) {
switch(event.keyCode) {
case 37: // Left
Ctrl.left = false;
break;
case 39: // Right
Ctrl.right = false;
break;
case 38:
Ctrl.up = false;
break;
case 40:
Ctrl.down = false;
break;
case 32:
Ctrl.space = false;
break;
default:
break;
}
}
};
Maybe one of your keys is activating an unwanted default behavior. You can try to add event.preventDefault(); to your event bindings.
check the jsFiddle
It depends on model of your keyboard. Some keyboards doesn't work with some key combinations. It's normal.

Categories

Resources