I'm trying to prevent players from pressing both left and right keys at the same time, since doing so will change both "isLeft" and "isRight" to true. I've tried the code below but it makes the controls really stiff, for example, if you were to let go of "D" too late before pushing "A", it will register "D" being released but would not register "A" being pressed (since A is pressed when "isRight" is true. Sorry if this analogy is too confusing...
I'm looking for a way to take input from pressing "A", and if "D" is still pressed after "A" is released, immediately take input from "D".
Thanks in advance!
function keyPressed()
{
if ((key == 'A' || keyCode == 37) && !isRight)
{
isLeft = true;
}
else if ((key == 'D' || keyCode == 39) && !isLeft)
{
isRight = true;
}
}
A solution to interpret left vs right when both keys are pressed is to listen for keyPressed and keyReleased. On keyReleased we can also check and see if the alternate key is already down. This approach allows the code to immeditally switch to the other key when both are down and one is released
var isLeft = false;
var isRight = false;
function setup(){
frameRate(10);
}
function keyPressed(){
if ((key == 'A' || keyCode == 37) && !isRight){
isLeft = true;
} else if ((key == 'D' || keyCode == 39) && !isLeft) {
isRight = true;
}
}
function keyReleased(){
if ((key == 'A' || keyCode == 37)){
isLeft = false;
if ((keyIsDown(16) && keyIsDown(68)) || keyIsDown(39)){
isRight = true;
}
}
else if ((key == 'D' || keyCode == 39)){
isRight = false;
if ((keyIsDown(16) && keyIsDown(65))|| keyIsDown(37)){
isLeft = true;
}
}
}
function draw(){
console.log( " isLeft: "+isLeft + " isRight: " + isRight);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
The keyIsDown detects if a key is being pressed. I'm not sure if it works for all characters, but it works for the arrow keys. If you add !keyIsDown(RIGHT_ARROW), then it sees if the Right arrow is down. If it's down, then the if isn't true, if it's false the if is true it's being run.
Tell me if this doesn't work.
function keyPressed()
{
if ((key == 'A' || keyCode == 37) && !isRight&&!keyIsDown(RIGHT_ARROW))
{
isLeft = true;
}
else if ((key == 'D' || keyCode == 39) && !isLeft!keyIsDown(LEFT_ARROW))
{
isRight = true;
}
}
Related
Im currently making a html5 multiplayer game with socket.io.
My problem is that i can only move my character in a straight line, while i also want to be able to move diagonal across my canvas. What i mean by this is if i press the 'a' and 'd' key, my character moves diagonally to the bottom right. With my current code my character only moves to the right or down.
//client, how i capture my keyboard input.
document.onkeydown = function(event){
console.log(`Keycode: ${event.which}`);
if(event.which == 68 || event.which == 39) //d of pijl rechts
sock.emit('keyPress', 'right');
else if(event.which == 83 || event.which == 40) //s of pijl naar beneden
sock.emit('keyPress','down');
else if(event.which == 65 || event.which == 37) //a of pijl naar links
sock.emit('keyPress','left');
else if(event.which == 87 || event.which == 38) // w of pijl naar omhoog
sock.emit('keyPress','up');
}
//server,
sock.on('keyPress', (keypress) => {
var currentUser = this[sock.id];
if (keypress == 'up') {
currentUser.y = currentUser.y - currentUser.speed;
}
else if (keypress == 'down') {
currentUser.y = currentUser.y + currentUser.speed;
}
else if (keypress == 'left') {
currentUser.x = currentUser.x - currentUser.speed;
}
else if (keypress == 'right') {
currentUser.x = currentUser.x + currentUser.speed;
}
});
setInterval(function(){
io.emit('update-players', Users);
},1000/30);
//client, how all players are drawn onto to canvas
sock.on('update-players', updatePlayers);
var updatePlayers= (Users) => {
ctx.clearRect(0,0,10000,10000);
Users.forEach((user) => {
var img = new Image();
img.src = 'Images/player.png';
ctx.drawImage(img,user.x,user.y,user.width,user.height);
ctx.font = "20px Courier New";
ctx.fillText(`${user.name}`,user.x,(user.y - 10))
}
});
sorry for my crappy english.
When we press two keys on the keyboard and hold them down, only the last key pressed gets repeated events in the keydown listener. So, for example, if you press DOWN and RIGHT "at the same time", only one will be repeatedly reported to the listener and the other will be ignored.
A better approach is to have listeners for the keydown and keydown events, like this:
var keyStates = {
up: false,
down: false,
left: false,
right: false
}
function updateKeyStates(code, value) {
if(code == 68 || code == 39) //d of pijl rechts
keyStates.right = value;
else if(code == 83 || code == 40) //s of pijl naar beneden
keyStates.down = value;
else if(code == 65 || code == 37) //a of pijl naar links
keyStates.left = value;
else if(code == 87 || code == 38) // w of pijl naar omhoog
keyStates.up = value;
}
document.addEventListener('keydown', function(event) {
console.log(`Pressed: ${event.which}`);
updateKeyStates(event.which, true);
});
document.addEventListener('keyup', function(event) {
console.log(`Released: ${event.which}`);
updateKeyStates(event.which, false);
});
So we basically have a boolean variable for each direction. You should send that information (keyStates) to the server and it should do the math based on which keys are down.
I need the keycodes for something but I don't know what kind of keycode it is, I couldn't find it anywhere else.
function keyDown(e) {
if (String.fromCharCode(e.keyCode) == "%") isLeft = true;
if (String.fromCharCode(e.keyCode) == "'") isRight = true;
}
function keyUp(e) {
if (String.fromCharCode(e.keyCode) == "%") isLeft = false;
if (String.fromCharCode(e.keyCode) == "'") isRight = false;
}
I figured out that % is left arrow and ' is the right arrow, could anyone tell me what kind of keycode thingy this is? or maybe how I could change it to a better one.
Thanks :)
You can easily find keycode values by googling for "javascript keycodes", or just use this website: keycode.info
The keycode for left arrow is 37, right arrow is 39.
In your code you converted e.keyCode to an ASCII character, which is unnecessary. Unsurprisingly, ASCII character #37 is %, #39 is '.
Just compare the keycode values directly:
function keyDown(e) {
if (e.keyCode == 37) isLeft = true;
if (e.keyCode == 39) isRight = true;
}
function keyUp(e) {
if (e.keyCode == 37) isLeft = false;
if (e.keyCode == 39) isRight = false;
}
You could use e.key, it returns value of the pressed key. So if you press left arrow key e.key would be "ArrowLeft" and if you press right arrow key e.key would be "ArrowRight".
You can lookup these codes Keycode table
or
check them interactively here: http://keycode.info/ or http://keycodes.atjayjo.com/
The function String.fromCharCode will then convert a unicode number into a character.
For cross browser compatibility you might want to check both the e.which and e.keyCode properties like below.
function(e) {
e = e || window.event;
var keyCode= e.which || e.keyCode;
var charStr = String.fromCharCode(keyCode);
alert("The keycode is: "+ keyCode + " and charCode is: " + charStr);
}
You don't need to get the character for those key codes, you could just compare them directly:
function keyDown(e) {
if (e.keyCode === 37) isLeft = true;
if (e.keyCode === 39) isRight = true;
}
function keyUp(e) {
if (e.keyCode === 37) isLeft = false;
if (e.keyCode === 39) isRight = false;
}
Anyway, keep in mind e.keyCode is deprecated, so e.key or e.code should be used instead, which also makes the code easier to understand. Also, you could use an object with boolean properties instead of individual booleans to make this scale better to more keys:
const pressedKeys = {};
document.onkeydown = ({ key }) => {
pressedKeys[key] = true;
console.log(Object.keys(pressedKeys).join(' + '));
};
document.onkeyup = ({ key }) => {
delete pressedKeys[key];
console.log(Object.keys(pressedKeys).join(' + '));
};
Just keep in mind some old browsers used non-standard codes, so left is usually 'LeftArrow ' and right is 'RightArrow', but on IE it's just 'Left' and 'Right' instead.
Also, if you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode you can use https://keyjs.dev. I will add information about these kinds of cross-browser incompatibilities soon!
Disclaimer: I'm the author.
I have a requirement where I have to prevent user from typing in shift+greater than in textbox.
I looked up in the ascii key code chart.I could see no ascii key for shift+greater than combination which renders ">" on the UI.
This is the code that i have tried so far.
$scope.isValidControlInputInteger = function (event) {
var keyCode = event.keyCode;
if (keyCode >= 48 && keyCode <= 57 && event.shiftKey) { // decimal numbers
return true;
} else if (keyCode >= 96 && keyCode <= 105) { // numerical pad
return true;
} else if (keyCode == 46 || keyCode == 8) { // delete and backspace
return true;
} else if (keyCode == 37 || keyCode == 39) { // arrow keys
return true;
}
else if (keyCode == 9) { // tab key
return true;
}
else {
return false;
}
};
A simple workaround that works better than checking for keyup is to just remove all instances of > upon changing the contents of the input field.
$("#field").on("keyup", function(e) {
$(this).val($(this).val().replace(/\>/g, ""))
});
Here's a fiddle.
I want to disable the ctrl key in the IE browser.I had tried some solution using javascript but nothing is working can someone please help me to find out the solution
document.onkeydown = function () {
if (event.keyCode == 17) alert('Ctrl Key is disabled');
};
document.onkeydown = function(e) {
if (e.altKey && (e.keyCode === 36)) {//Alt+home blocked.
return false;
}
if (e.altKey && (e.keyCode === 70)) {//Alt+f blocked.
return false;
}
};
function hookKeyboardEvents(e) {
// get key code
var key_code = (window.event) ? event.keyCode : e.which;
// case :if it is IE event
if (window.event)
{
if (!event.shiftKey && !event.ctrlKey) {
window.event.returnValue = null;
event.keyCode = 0;
}
}
// case: if it is firefox event
else
e.preventDefault();
}
window.document.onkeydown = hookKeyboardEvents;
function Disable_Control_C() {
var keystroke = String.fromCharCode(event.keyCode).toLowerCase();
if (event.ctrlKey && (keystroke == 'c' || keystroke == 'v' || keystroke == 'p' || keystroke == 's' || keystroke == 'u')) {
alert("this function is disabled");
event.returnValue = false; // disable Ctrl+C
}
}
<body onkeydown="javascript:Disable_Control_C()">
this is what i do it to run in the IE...
While working with the multiple keypress events i found this code which worke fine
$(document).bind('keypress', function(event) {
if( event.which === 65 && event.shiftKey ) {
alert('you pressed SHIFT+A');
}
});
But to make it to work wth combinig with windows key... like
event.which === 65 && event.windowsKey
it failed...
Is there any option to make it work with windows key?
if it is a mac machine there is no key as windows..so what could be the alternate option for windows key in mac
Use keyup event.
On a Mac left Command is which = 91, right Command is which = 93. I can't tell what are those on Windows, but you can test it yourself. As #ian commented they should be 91 and 92 respectively.
To test
$(document).on('keyup', function(e) {
var modKey = "";
if (e.shiftKey) modKey += "shiftKey,";
if (e.ctrlKey) modKey += "ctrlKey,";
if (e.altKey) modKey += "altKey,";
if (e.metaKey) modKey += "metaKey,";
console.log ("which: " + e.which + " modkey: " + modKey );
});
UPDATE: Try use keydown event and event.metaKey
$(document).on('keydown', function(e) {
if(e.which === 65 && event.metaKey ) {
console.log ("You pressed Windows + A");
}
});
Remember the key you pressed before. Like if you press shift. get a boolean or something to shiftPressed = true on a onKeyRelease make it false again. That way you can check if shiftPressed == true && aPressed == true before doing something
I made something a while ago for a little WASD game. Perhaps it makes more sense if you see the code:
var up = false;
var down = false;
var left = false;
var right = false;
function keyUp(e) {
keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode == 37 || keyCode == 65) {
left = false;
}
if (keyCode == 38 || keyCode == 87) {
up = false;
}
if (keyCode == 39 || keyCode == 68) {
right = false;
}
if (keyCode == 40 || keyCode == 83) {
down = false;
}
}
function forceStopMoving() {
left = false;
up = false;
right = false;
down = false;
}
function keyDown(e) {
keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode == 37 || keyCode == 65) {
left = true;
}
if (keyCode == 38 || keyCode == 87) {
up = true;
}
if (keyCode == 39 || keyCode == 68) {
right = true;
}
if (keyCode == 40 || keyCode == 83) {
down = true;
}
}