Adding a cool down to a javascript key press - javascript

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.

Related

Is there a way to convert a function with multiple if statements to an arrow function?

I want to use arrow function syntax with a few code snippets I've been working with. I was successful until I reached one in particular with multiple if statements. I know this might come up as a duplicate question, but after looking through some of the previous answers, I still can't find a working syntax.
I looked at a few of the duplicate answers on stack overflow and tried the formats suggested but nothing works. I also get no errors.
function keydownHandler(event) {
"use strict"
// handle user keyboard input
if (event.keyCode == UP) {
rocket.y -= velocity;
}
if (event.keyCode == LEFT) {
rocket.x -= velocity;
}
if (event.keyCode === DOWN) {
rocket.y += velocity;
}
if (event.keyCode == RIGHT) {
rocket.x += velocity;
}
render( );
}
//===========One of many formats i've tried=============================
var keydownHandler = event => {
if (event.keyCode == UP) {
rocket.y -= velocity;
}
if (event.keyCode == LEFT) {
rocket.x -= velocity;
}
if (event.keyCode === DOWN) {
rocket.y += velocity;
}
if (event.keyCode == RIGHT) {
rocket.x += velocity;
}
render( );
}
You could take an object with a default function for unknown keyCode.
const
directions = {
UP: () => rocket.y -= velocity,
LEFT: () => rocket.x -= velocity,
DOWN: () => rocket.y += velocity,
RIGHT: () => rocket.x += velocity,
default: () => {}
};
Call with
(directions[event.keyCode] || directions.default)();
You could use the Conditional (ternary) operator if you want to turn it into a 1 liner. This will only allow 1 key press at a time though
const keydownHandler = (event) => {event.keyCode === UP ? rocket.y -= velocity : event.keyCode === LEFT ? rocket.x -= velocity : event.keyCode === DOWN ? rocket.y += velocity : event.keyCode === RIGHT ? rocket.x += velocity : 0; render();}
This code is untested.
But for readablity I'd recommend using a switch statement or partial ternary operation
const keydownHandler = (event) => {
// this prevents the rocket from going up and down at the same time
rocket.y += event.keyCode === UP ? velocity : event.keyCode === DOWN ? -velocity : 0;
// this prevents the rocket from going left and right at the same time. if both keys are pressed the rocket will turn right
rocket.x += event.keyCode === RIGHT ? velocity : event.keyCode === LEFT ? -velocity : 0;
render();
};
This section of code will prevent the rocket from going up and down at the same time. If both keys are pressed it will go up. The same goes for the left and right.

Player movement in javascript with socket.io

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.

Need help getting loop to work with an onkeydown event in javascript

I need help figuring out how to get the loop to work properly with onKeydown. Right now, I'm having issues where if you press the key once, it outputs 10 message in one go.
var i = 0;
do {
if (document.onkeydown = keyPress) {
i += 1;
console.log(i);
}
} while (i < 5);
function keyPress(m) {
if (m.keyCode == '38') {
i
document.write("you moved North" + "<br>");
//up arrow
} else if (m.keyCode == '40') {
document.write("you moved South" + "<br>");
//down arrow
} else if (m.keyCode == '37') {
document.write("you moved West" + "<br>");
//left arrow
} else if (m.keyCode == '39') {
document.write("you moved East" + "<br>");
//right arrow
}
}
Not sure if this is your problem, but given your code, document.onkeydown is always going to equal keyPress. Switch:
if (document.onkeydown = keyPress) {
...
}
To:
if (document.onkeydown == keyPress) {
...
}

How to use spacebar and if statements in JS?

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
}
}

Javascript error: I have a unexpected end of input on my first line, with no apparent problems, but I'm getting a message and the whole canvas stops

I put in the entire thing just in case
I went into chrome and looked for errors, and it wasnt working either so I checked, apparently the first line has a problem. I kept the first 6 lines and deleted all else then it worked fine, so I went to SublimeText2 and searched for every ) and } in the code.
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasJet = document.getElementById('canvasJet');
var ctxJet = canvasJet.getContext('2d');
var jet1;
var fps = 17;
var drawInterval;
var imgSprite = new Image();
imgSprite.src = 'SpriteSheet.png'
imgSprite.addEventListener('load',init,false);
function init() {
drawBg();
startDrawing();
jet1 = new Jet();
document.addEventListener('keydown',checkKeyDown,false);
document.addEventListener('keyup',checKeyUp,false);
}
function draw() {
jet1.draw();
}
function startDrawing() {
stopDrawing();
drawInterval = setInterval(draw,fps);
}
function stopDrawing() {
clearInterval(setInterval);
}
Jet.prototype.draw = function() {
clearCtxJet();
ctxJet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
};
function Jet() {
this.srcX = 0;
this.srcY = 0;
this.drawX = 200;
this.drawY = 200;
this.width = 96;
this.height = 30;
}
function drawJet() {
}
function drawBg() {
ctxBg.drawImage(imgSprite,96,0,800,500,0,0,800,500)
}
function clearCtxBg() {
ctxBg.clearRect(0,0,800,500);
}
function clearCtxJet() {
ctxJet.clearRect(0,0,800,500);
}
function checkKeyDown(e) {
var keyID = (e.keyCode) ? e.keyCode : e.which;
if (keyID === 38) { // 38 is up key
alert('up arrow was pressed');
e.preventDeafault();
}
if (keyID === 39) { // 39 is right key
e.preventDeafault();
}
if (keyID === 40) { // 40 is down key
e.preventDeafault();
}
if (keyID === 37) { // 37 is left key
e.preventDeafault();
}
function checkKeyup(e) {
var keyID = (e.keyCode) ? e.keyCode : e.which;
if (keyID === 38) { // 38 is up key
alert('up arrow was pressed');
e.preventDeafault();
}
if (keyID === 39) { // 39 is right key
e.preventDeafault();
}
if (keyID === 40) { // 40 is down key
e.preventDeafault();
}
if (keyID === 37) { // 37 is left key
e.preventDeafault();
}
}
I assume you're showing only parts of the code so there's no way of knowing whether this is the actual error, but both checkKeyup and checkKeydown are missing closing braces.
I recommend installing Package Control for Sublime Text 2 and then using it to install SublimeLinter which will be able to check your code for you and point out missing semicolons and braces.
It would be nice to see full code in http://jsfiddle.net

Categories