How to use spacebar and if statements in JS? - javascript

I am making a game based off of a tutorial at http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/ it is going well but I wanted to make the function that reads if the two items are touching only happen when the space bar is pressed.
if (hero.x <= (monster.x + 32)
&& monster.x <= (hero.x + 32)
&& hero.y <= (monster.y + 32)
&& monster.y <= (hero.y + 32)) {
++monstersCaught;
reset();
}
if (hero.x <= (tack.x + 32)
&& tack.x <= (hero.x + 32)
&& hero.y <= (tack.y + 32)
&& tack.y <= (hero.y + 32)) {
monstersCaught -= monstersCaught;
reset();
}
if (monstersCaught > 10) {
monstersCaught -= 10;
}
How should I fix the
if (hero.x <= (tack.x + 32)
&& tack.x <= (hero.x + 32)
&& hero.y <= (tack.y + 32)
&& tack.y <= (hero.y + 32)) {
monstersCaught -= monstersCaught;
reset();
}
so that it only goes if the space bar is pressed?

Most easy way is to know at any moment the status of your keyboard : for that you have to listen to keyboard events and update an array containing the status of each key.
This will lead to something like :
window.keyStates = []; // now you can use keyStates anywhere.
// good enough since you seem to be in the first steps.
window.addEventListener('keydown',
function(e) { keyStates[e.keyCode || e.key] = true;} );
window.addEventListener('keyup',
function(e) { keyStates[e.keyCode || e.key] = false;} );
Once you have done that, you can test anywhere, anytime, the status of the space key with :
if (keyStates[32] == true) { ... }
you might prefer, for readability, define a key object that will hold the few keycodes you use :
window.key = {
space : 32,
enter : 13,
left : 37,
up : 38,
right : 39,
down : 40
}
that way, you can write :
if ( keyStates[key.space] == true ) {
...
}
which is more easy to grasp.
(Rq : if you search for keycodes, looking here is one way : https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent )

If you use jQuery you can do something similar to this:
$(window).keypress(function(e) {
if (e.which === 32) {
//do your logic here
}
});
32 is the keycode for spacebar
Or in just javascript (Run this code in Document ready as displayunicode(event)):
function displayunicode(e){
var unicode=e.keyCode? e.keyCode : e.charCode;
if(unicode == 32){
//do your code
}
}

Related

JS - Why isnt the second value in my "or" equation recognised

im trying to create a function that will move an png image either up, down, left or right by the user either pressing WASD or the Arrow Keys. At the moment i have figured out a way to move the item using WASD however when i introduce the "or" operand and use the Key.Code for the arrow keys the arrow keys aren't recognised even though it will still recognise WASD
<body>
<div class="scene">
<div class="rocket">
<img src="rocket.png" alt="" />
</div>
</div>
<script src="script.js"></script>
document.addEventListener("keydown", (e) => {
var rocket = document.querySelector(".rocket");
let speed = 10;
if (event.keyCode == (87 || 38) && rocket.offsetTop > 100) {
rocket.style.top = `${rocket.offsetTop - speed}px`;
}
if (event.key == "s" && rocket.offsetTop < window.innerHeight - 300) {
rocket.style.top = `${rocket.offsetTop + speed}px`;
}
if (event.key == "a" && rocket.offsetLeft > 50) {
rocket.style.left = `${rocket.offsetLeft - speed}px`;
}
if (event.key == "d" && rocket.offsetLeft < window.innerWidth - 125) {
rocket.style.left = `${rocket.offsetLeft + speed}px`;
}
if (event.key == " " && rocket.offsetTop > 100) {
rocket.style.top = `${rocket.offsetTop - 200}px`;
}
console.log(event.keyCode);
});
This expression:
87 || 38
Evaluates to 87. Every time. Which means this expression:
event.keyCode == (87 || 38)
Compares the value to 87. Every time.
Don't think of these logical conditions as intuitive human language. They need to be built as individual logical expressions which individually evaluate to a value. What you're looking for is this:
(event.keyCode == 87 || event.keyCode == 38)
You should try
if ((event.keyCode == 87 || event.keyCode == 38) && rocket.offsetTop > 100)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

I want to perform different operation processes alternately in order with the same key operation

For example, you can start with a specific key and stop with a click or another key,
// Alt + Shift + ↓ Auto scroll
document.addEventListener("DOMContentLoaded", (l) => {
var m;
setInterval(m);
$(window).keydown((e) => {
//pattern 1
if (e.altKey && e.shiftKey && e.keyCode == 40) {
if (!m) {
m = setInterval((s) => {
scrollBy(0, s || 1);
}, 35);
}
}
$(document).on('click', () => {
clearInterval(m);
m = undefined;
});
//pattern 2
setInterval(m);
if (e.altKey && e.shiftKey && e.keyCode == 40) {
if (!m) {
m = setInterval((s) => {
scrollBy(0, s || 1);
}, 35);
}
}
if (e.keyCode == 96) { //ten key of「0」key
clearInterval(m);
m = undefined;
}
//}, false);
});
});
like this:
Attempting to process start and stop with the same key will not work.
In the example below
Start with Alt + Shift + ↓,
Stop as well
I want to do it with Alt + Shift + ↓. How can I correct it to implement the desired function?
The operating environment uses a third-party extension of the Chrome WEB store.
if i have understood what you want, you want to use the same keys to start and stop so, to do that you have to use a sort of toggle:
var timer;
var last_state = "keyup";
var param = 10;
$(window).on("keydown keyup", (e) => {
if (e.type == "keyup" && e.which == 40) {
last_state = "keyup";
}
if (e.type == "keydown" && e.type != last_state && e.altKey && e.shiftKey && e.which == 40) {
last_state = e.type;
if (!timer) {
timer = setInterval(() => {
scrollBy(0, param || 1);
}, 35);
} else {
clearInterval(timer);
timer = undefined;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Adding a cool down to a javascript key press

I have a Jquery problem today using key Codes, my code dumb below
$(function() {
var distance = 0;
$('.right').click(function() {
distance -= 100;
$('#container').css('transform', 'translateX(' + distance + '%)')
console.log(distance);
});
$('.left').click(function() {
distance += 100;
$('#container').css('transform', 'translateX(' + distance + '%);')
console.log(distance);
});
$(window).keypress(function (e) {
var code = e.keyCode || e.which;
if(code == 13) {
$('.right').trigger('click')
}
if(code == 9) {
$('.right').trigger('click')
}
if(code == 32) {
$('.right').trigger('click')
}
if(code == 39) {
$('.right').trigger('click')
}
});
});
So I am having some trouble making the arrow key presses work.
if(code == 32) {
$('.right').trigger('click')
}
if(code == 39) {
$('.right').trigger('click')
}
Not only that but I can't seem to figure out a way to put a delay on it (1s) so it doesn't add a few hundred to the distance var when I only want it to do it once, so lets say instead of delay, a cool down.
UPDATE
While I'm at it I would like to ask if anyone has any solutions to putting a maximum and miniumum amount on
var distance = 0;
Look at debounce and throttle mechanisms described here. It should help you in achieving the delay/cool down.

Jquery Auto change focused text box via button

i am creating a system where there will be a pacific mobile view. From this you will be able to press one of 3 buttons and it will emulate a key press on a keyboard.
Currently for the desktop version the focused box changes like this:
$('.today').keydown(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191, 8, 40, 38]) === -1) { // 8 is backspace
e.preventDefault();
}
});
$('.today').keyup(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191, 8, 40, 38]) === -1) { // e, x, / respectively // don't print the character
return false;
}
var self = $(this);
var currentInput = self.data('number');
var next = $(currentInput + 1);
var previous = $(currentInput - 1);
var keyCode = e.keyCode || e.which;
var num = self.data('number') + 1;
var nom = self.data('number') - 1;
if(('input.today[data-number="' + num +'"]').length && keyCode === 40)
$('input.today[data-number="' + num +'"]').focus()
else if(('input.today[data-number="' + nom +'"]').length && keyCode === 38)
$('input.today[data-number="' + nom +'"]').focus();
else if(('input.today[data-number="' + num +'"]').length && self.val().length == self.attr('size')) {
$('input.today[data-number="' + num +'"]').focus();
}
});
For the buttons I have this piece of code:
$("button").click(function() {
$(".today").focus();
var e = jQuery.Event("keydown");
e.which = 47; // # Some key code value
$("input").val(String.fromCharCode(e.which));
$("input").trigger(e);
});
$('input').keypress(function(e){
console.log('Yes keydown triggered. ' + e.which)
});
This fills the text box and it will change to next, but then when i press it will focus back to original... Any ideas.
$(".today").focus();
suggests your using classes as the identifier, are your ID's unique?

Optimizing jQuery Hotkeys

So I have a web app which uses all the hot keys from A to Z.
Each hot key is used for a tab. So for example:
I have 20 tabs:
#tab1, #tab2, #tab3, #tab4 etc. All tabs get a class of .tabs.
So for the hotkeys to work I made this:
if (e.keyCode == 65) {$('.tabs:not(#tab1)').hide();$("#tab1").fadeIn();}
if (e.keyCode == 66) {$('.tabs:not(#tab2)').hide();$("#tab2").fadeIn();}
if (e.keyCode == 67) {$('.tabs:not(#tab3)').hide();$("#tab3").fadeIn();}
if (e.keyCode == 68) {$('.tabs:not(#tab4)').hide();$("#tab4").fadeIn();}
if (e.keyCode == 69) {$('.tabs:not(#tab5)').hide();$("#tab5").fadeIn();}
if (e.keyCode == 70) {$('.tabs:not(#tab6)').hide();$("#tab6").fadeIn();}
if (e.keyCode == 71) {$('.tabs:not(#tab7)').hide();$("#tab7").fadeIn();}
//etc till keycode 81 and tab20.
So, is there a better optimizing way to make this so it will be written in less characters? Since on each line I'm using twice the the same ID.
Edit/Note: Sorry, the actual tab ID's are random names.
Thanks
Something like this perhaps:
if(e.keyCode >= 65 && e.keyCode <= 81) {
var tab = e.keyCode - 65 + 1;
$('.tabs:not(#tab' + tab + ')').hide();
$('#tab' + tab).fadeIn();
}
I don't see how keycode 81 is supposed to be tab20 though, wouldn't that be tab17?
Update: If your tab ids can be anything at all then just throw them in an array:
var tab_ids = [ 'where', 'is', 'pancakes', 'house', ... ];
if(e.keyCode >= 65 && e.keyCode <= 81) {
var tab = tab_ids[e.keyCode - 65];
$('.tabs:not(#' + tab + ')').hide();
$('#' + tab).fadeIn();
}
If you also have gaps in they keycodes then use an object instead of an array:
var tab_ids = { 65: 'where', 70: 'is', 72: 'pancakes', 73: 'house', ... };
var tab = tab_ids[e.keyCode];
if(tab) {
$('.tabs:not(#' + tab + ')').hide();
$('#' + tab).fadeIn();
}
$('.tabs:not(#tab' + (e.keyCode - 64) + ')').hide();
$("#tab" + (e.keyCode - 64)).fadeIn();
Just replace all these if statements with this code
$('.tabs:not(#tab'+(e.keyCode-64)+')').hide();
$("#tab"+(e.keyCode-64)).fadeIn();

Categories