detecting two keyboard buttons in javascript - javascript

im writing a simple canvas game and want to be able to move my character diagonally on the screen. how do I detect two keys pressed say up and right?
heres my code so far-
function keyHit(evt){
switch (evt.keyCode) {
case 38: /* Up arrow was pressed */
if (player2y >= 1){
player2y -= 4;
} else {player2y = 0;}
break;
case 40: /* Down arrow was pressed */
if (player2y <= 364){
player2y += 4;
} else { player2y = 365;}
break;
case 37: /* Left arrow was pressed */
if (player2x >= 1){
player2x -= 4;
} else {player2x = 0;}
break;
case 39: /* Right arrow was pressed */
if (player2x <= 665){
player2x += 4;
} else {player2x = 666;}
break;
}
}

Trap "keydown" and "keyup" events and maintain the list of keys that are currently pressed. Example:
pressed = {}
window.onkeydown = function(e) {
pressed[e.keyCode] = 1
handler(Object.keys(pressed).sort())
}
window.onkeyup = function(e) {
delete pressed[e.keyCode];
handler(Object.keys(pressed).sort())
}
function handler(pressed) {
document.getElementById("log").value = pressed
if(pressed == "38,39")
alert("Up+Right pressed!")
}
<textarea id="log"></textarea><br>click here first, then press some keys

Related

Keyboard Arrow Key Controls in Javascript

function control()
{
var ship = document.getElementById("ship");
document.onkeydown = function(e) {
switch (e.keyCode) {
case 38:
ship.style.top += "5%";
break;
case 40:
ship.style.top -= "5%";
break;
default:
break;
}
}
}
setInterval(control,1000);
This code is not working.
The object I'm trying to move is not moving when I'm pressing the Up & Down Arrow Key.
You can't do
ship.style.top += "5%";
because ship.style.top value is not a number but a string. the += opérator is concatening strings here.
You should do something like that:
const ship = document.getElementById("ship");
document.onkeydown = function (e) {
let winHeigth = window.innerHeight;
let top = ship.style.top;
switch (e.code) {
case "ArrowUp":
ship.style.top = (Number(top.substring(0, top.length - 2)) - (winHeigth / 20)) + "px";
break;
case "ArrowDown":
ship.style.top = (Number(top.substring(0, top.length - 2)) + (winHeigth / 20)) + "px";
break;
default:
break;
}
}
The position attribute of the "ship" must be like "relative".
By the way, e.keyCode is deprecated, you can use e.code instead ^^

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/

Categories

Resources