Event .key switch for a video game - javascript

i want to change the way my Js game works, basically the game does not recognize input whenever the language is not english with no Capital letters ( only when the event.key is equal to wasd ) how can i fix this bug ?
thanks !
window.addEventListener('keydown', (event) => {
if (!player.isDead){
switch (event.key) {
case 'w':
keys.d.pressed = true;
player.lastkey = 'd';
break;
case 'a':
keys.a.pressed = true;
player.lastkey = 'a';
break;
case 'w':
if(player.position.y > 0)
{
player.velocity.y = -10;
}
break;
case ' ':
player.Attacking();
if(player.lastkey === 'd'){player.SwitchSprite('punch')}
else{player.SwitchSprite('fpunch')}
break;
}
}

You should use the event.code or event.keyCode properties to stay language independent;
switch (event.code) // <- not event.key
case "KeyW": // <- not 'w'
...

Related

How to combine key codes to work together in javascript

E.g. I have the following script
<script>
document.onkeydown = function(evt){
evt = evt || window.event;
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
};
</script>
When I press
shift + keycode
to call a function specified, I am just new to JavaScript and I code JavaScript based on other languages I know
Thanks and Regards
Check .shiftKey which returns a boolean indicating if the key is pressed. Placing this conditional around your switch will prevent any events from occurring unless the key is pressed in combination with shift.
document.onkeydown = function(evt){
evt = evt || window.event;
if(evt.shiftKey){
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
}
};
You can detect the shift key separately. e.g. if you want to call createNewFile with the shift key down:
if(evt.shiftKey && evt.keyCode == 67) {
createNewFile();
}
In your code, you could do something like:
evt = evt || window.event;
switch (evt.keyCode){
case 67:
if (evt.shiftkey) {
// Do something special for shift mode.
} else {
createNewFile();
}
break;
...

Keyboard Error Sound when catching KeyCode

I'm programming something withe Javascript which captures keyboard input, but the problem is that every time the user presses a key there an error sound. How can I disable it?
#Polaris878
function KeyPressed(e)
{
if (!e) e = window.event;
if (e.which)
{
keycode = e.which
}
else if (e.keyCode)
{
keycode = e.keyCode
}
switch (keycode)
{
case 49:
key = "1";
break;
case 50:
key = "2";
break;
case 51:
key = "3";
break;
case 52:
key = "4";
break;
case 53:
key = "5";
break;
case 54:
key = "6";
break;
case 55:
key = "7";
break;
case 56:
key = "8";
break;
case 57:
key = "9";
break;
case 48:
key = "0";
break;
default:
key = "";
return false;
break
}
if (keys == "NULL")
{
keys = key
}
else
{
keys = keys + key
} if (keys.length >= 5)
{
document.formular.submit();
}
document.formular.code.value = keys;
}
var keys = "";
document.onkeydown = KeyPressed

Simplifying a switch case in JavaScript

I have a rather repetitive switch case statement and in my quest to learn the simplest way of doing things, I wanted to turn to SO and see if there is a more elegant solution to the following:
switch(id)
{
case 'ib-02a':
if(direction == 'left')
setHash('ib-02b');
break;
case 'ib-02b':
if(direction == 'right')
setHash('ib-02a');
if(direction == 'left')
setHash('ib-02c');
break;
case 'ib-02c':
if(direction == 'right')
setHash('ib-02b');
if(direction == 'left')
setHash('ib-02d');
break;
case 'ib-02d':
if(direction == 'right')
setHash('ib-02c');
break;
case 'ib-03a':
if(direction == 'left')
setHash('ib-03b');
break;
case 'ib-03b':
if(direction == 'right')
setHash('ib-03a');
if(direction == 'left')
setHash('ib-03c');
break;
case 'ib-03c':
if(direction == 'right')
setHash('ib-03b');
if(direction == 'left')
setHash('ib-03d');
break;
case 'ib-03d':
if(direction == 'right')
setHash('ib-03c');
break;
case 'pb-05a':
if(direction == 'left')
setHash('pb-05b');
break;
case 'pb-05b':
if(direction == 'right')
setHash('pb-05a');
if(direction == 'left')
setHash('pb-05c');
break;
case 'pb-05c':
if(direction == 'right')
setHash('pb-05b');
if(direction == 'left')
setHash('pb-05d');
break;
case 'pb-05d':
if(direction == 'right')
setHash('pb-05c');
break;
}
I'm reading swipe events, and if the ID of the element I am swiping on matches either ib-02*, ib-03*, or pb-05*, I am calling a setHash function for the appropriate ID. If I'm swiping on *a, I swipe left to *b. If I'm swiping on *b, I swipe right to *a and left to *c. So on and so forth, always between *a and *d.
There must be a less repetitive way to do this, but I'm not sure exactly what the best approach is.
How about mapping them to an object? Then just use the setHash with the retrieved value.
var ids = {
'pb-05c' : {
left : 'pb-05d',
right : 'pb-05b'
}
...
}
function setHashes(id,direction){
if(id && ids[id]){
id = ids[id];
if(direction && id[direction]){
setHash(id[direction]);
}
}
}
It's all retrieval and no condition evaluation, which can be good for performance.
There are 4 major cases that are a, b, c and d, you can base your switch statement on these strings, try this:
var c = id.slice(0, 5); // "ib-02" or "ib-03" or "ib-04" ...
var which = id.slice(-1); // "a" or "b" or "c" or "d"
switch(which) {
case 'a':
if(direction == 'left')
setHash(c+'b');
break;
case 'b':
if(direction == 'right')
setHash(c+'a');
if(direction == 'left')
setHash(c+'c');
break;
case 'c':
if(direction == 'right')
setHash(c+'b');
if(direction == 'left')
setHash(c+'d');
break;
case 'd':
if(direction == 'right')
setHash(c+'c');
break;
}
You can make the whole thing data table driven like this:
var logicData = {
// format is the id first and then an array with the left, then right value for the hash
// leave an item as an empty string if you don't ever want to go that direction
'ib-02a': ['ib-02b', ''],
'ib-02b': ['ib-02c', 'ib-02a'],
'ib-02c': ['ib-02d', 'ib-02d']
// fill in the rest of the data table here
};
function setNewHash(id, direction) {
var hash, data = logicData[id];
if (data) {
if (direction == 'left') {
hash = data[0];
} else if (direction == 'right') {
hash = data[1];
}
if (hash) {
setHash(hash);
}
}
}
id='ib-02a'; //you have string id, this one is for demo
id=[id.slice(0,--id.length), id.charAt(--id.length)];
switch(id[1]){
case 'a':
if(direction == 'left'){setHash(id[0]+'b');}
break;
case 'b':
if(direction =='right'){setHash(id[0]+'a');}
if(direction == 'left'){setHash(id[0]+'c');}
break;
case 'c':
if(direction == 'right'){setHash(id[0]+'b');}
if(direction == 'left'){setHash(id[0]+'d');}
break;
case 'd':
if(direction == 'right'){setHash(id[0]+'c');}
break;
}
If case b and c are only 'left' or 'right' you could use an else in those if statements.
I like the general direction of undefined and GitaarLab where they actually solved the algorithm and just implemented the algorithm. To review, the algorithm is basically that left increments the final letter and right decrements the final letter of the id, but you don't go below a or above d. So, I did a compact implementation of that where I convert the last letter to a number and increment or decrement it directly rather than using if/else or case statements:
function setNewHash(id, direction) {
var base = id.substr(0, 5);
var tag = id.charCodeAt(5), newTag;
var nav = {left: 1, right: -1};
var delta = nav[direction];
if (delta) {
tag += delta;
newTag = String.fromCharCode(tag);
if (newTag >= 'a' && newTag <= 'd') {
setHash(base + newTag);
}
}
}
Working test case: http://jsfiddle.net/jfriend00/gwfLD/
You could chunk up the id into different parts, then rebuild them right before you do setHash.
function chunkId(id) {
// use a regex or string split or something to convert
// "ib-05a" to ["ib-05", "a"]
return ["ib-05", "a"];
}
function next(str) {
// return the next letter in the alphabet here
return "b";
}
function prev(str) {
// return the prev letter in the alphabet here
return "b";
}
function swipe (id, direction) {
var array = chunkId(id);
// you can only swipe left if not on "d"
if (direction === "left" && id[1] != "d") {
setHash(id[0] + next(id[1])); // build hash based on next character
}
// you can only swipe right if not on "a"
if (direction === "right" && id[1] != "a") {
setHash(id[0] + prev(id[1])); // build hash based on prev character
}
}
You can switch the id and direction checks to make it clearer:
switch (direction) {
case 'left':
switch (id) {
case 'ib-02a': setHash('ib-02b'); break;
case 'ib-02b': setHash('ib-02c'); break;
case 'ib-02c': setHash('ib-02d'); break;
case 'ib-03a': setHash('ib-03b'); break;
case 'ib-03b': setHash('ib-03c'); break;
case 'ib-03c': setHash('ib-03d'); break;
case 'pb-05a': setHash('pb-05b'); break;
case 'pb-05b': setHash('pb-05c'); break;
case 'pb-05c': setHash('pb-05d'); break;
}
break;
case 'right':
switch (id) {
case 'ib-02b': setHash('ib-02a'); break;
case 'ib-02c': setHash('ib-02b'); break;
case 'ib-02d': setHash('ib-02c'); break;
case 'ib-03b': setHash('ib-03a'); break;
case 'ib-03c': setHash('ib-03b'); break;
case 'ib-03d': setHash('ib-03c'); break;
case 'pb-05b': setHash('pb-05a'); break;
case 'pb-05c': setHash('pb-05b'); break;
case 'pb-05d': setHash('pb-05c'); break;
}
break;
}
Then you can simplify if by splitting the id:
var first = id.substr(0, 5);
var last = id.substr(6);
switch (direction) {
case 'left':
switch (last) {
case 'a': setHash(first + 'b'); break;
case 'b': setHash(first + 'c'); break;
case 'c': setHash(first + 'd'); break;
}
break;
case 'right':
switch (last) {
case 'b': setHash(first + 'a'); break;
case 'c': setHash(first + 'b'); break;
case 'd': setHash(first + 'c'); break;
}
break;
}

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