requestAnimationFrame not working as intended Javascript - javascript

I'm making a game in which a player character moves left and right.
Since simply using an onKeyDown eventListener had my character move in a choppy fashion, and with a slight delay, I tried using requestAnimationFrame to call the movement function as often as possible, as suggested by another answer(How can I move my JS objects smoothly using keyboard input?)
however, that has changed nothing.
Here is my Javascript Code
var NodoCampo = document.getElementById("campo");
var NodoGiocatore = null;
var Left = false;
var Right = false;
var FRAMERATE = 20;
//cache giocatore
var LARG_GIOCATORE = 30;
var ALT_GIOCATORE = 30;
var X_GIOCATORE = 300;
var Y_GIOCATORE = 1100;
var VEL_GIOCATORE = 10;
function mostra_giocatore() {
if (NodoGiocatore === null) {
NodoGiocatore = document.createElement('div');
NodoGiocatore.setAttribute ('id', 'player');
NodoCampo.appendChild (NodoGiocatore);
}
NodoGiocatore.style.marginLeft = (X_GIOCATORE - LARG_GIOCATORE) + 'px';
NodoGiocatore.style.marginTop = (Y_GIOCATORE - ALT_GIOCATORE) + 'px';
}
function muovi() {
if (Left) {
X_GIOCATORE = X_GIOCATORE - VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
else if (Right) {
X_GIOCATORE = X_GIOCATORE + VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
}
function stop() {
Left = false;
Right = false;
}
function interfaccia(e) {
//freccia sinstra
if (e.keyCode === 37) {
X_GIOCATORE = X_GIOCATORE - VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
//freccia destra
else if (e.keyCode === 39) {
X_GIOCATORE = X_GIOCATORE + VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
}
function inizia() {
mostra_giocatore();
requestAnimationFrame(muovi);
}
window.document.onkeypress = interfaccia;
window.document.onkeyup = stop;

Your choppy movement is likely a result of the amount you are moving the player on each frame with VEL_GIOCATORE. Try reducing this amount to observe smoother movement.
The delay you are experiencing is likely due to your operating system or browsers individual settings on how key presses should repeat. You can work around this by implementing your own key tracking -- it looks like you've started to experiment with this. Track the state of your left and right keys by updating a boolean value in onkeydown and onkeyup event listeners.
var keys = {
left: false,
right: false
};
window.document.onkeydown = function (e) {
if (e.keyCode === 37) {
keys.left = true;
} else if (e.keyCode === 39) {
keys.right = true;
}
window.document.onkeyup = function (e) {
if (e.keyCode === 37) {
keys.left = false;
} else if (e.keyCode === 39) {
keys.right = false;
}
Then, in your muovi function, check the state of these variables to determine if you should update the position of the player.

Related

html5 currentTime and volume changes not taking effect

I must be doing something wrong. Trying to set arrow hotkeys for videos to skip through the timeline and adjust the volume. Console logs return the desired new values, but they are not set.
document.onkeydown = function(e) {
var vid = document.getElementsByTagName('VIDEO');
if (vid.length) {
var vol = vid[0].volume;
var time = vid[0].currentTime;
var start = vid[0].seekable.start(0) + 10;
var end = vid[0].seekable.end(0) - 10;
if (e.keyCode === 37) {
if (start < time) {
time = time - 10;
console.log(time);
}
e.preventDefault();
}
if (e.keyCode === 38) {
if (vol < 1.0) {
vol = vol + 0.1;
console.log(vol);
}
e.preventDefault();
}
if (e.keyCode === 39) {
if (time < end) {
time = time + 10;
console.log(time);
}
e.preventDefault();
}
if (e.keyCode === 40) {
if (0.0 < vol) {
vol = vol - 0.1;
console.log(vol);
}
e.preventDefault();
}
}
};
You are not updating the vid.
Let's take an instance for volume updation.
What's happening here is you are taking value out of vol[0].volume into another variable 'volume' and upon event you are updating volume as a variable not vid, which you are using actually. Same goes for other keys (start, end and time).
Update vid as well.

trigger key after x seconds (key is constantly pressed)

The code works in the following way:
- holding shoot/drop button generate bullet and the bomb that is drawn/shown in canvas,
- it executes all the time in the function draw that refreshes around 60times per second.
Instead I want to set sth as:
- setInterval(shoot, 1000);
- setInterval(drop, 2000);
so it should be like:
- when user presses the key, it creates the bullet/bomb with the interval of 1/2 seconds
- it should all happen without realising the key
Below I provide the sample code:
let left = false;
let up = false;
let right = false;
let down = false;
let shoot = false;
let drop = false;
document.onkeydown = function (e) {
if (e.keyCode == 37) left = true;
if (e.keyCode == 38) up = true;
if (e.keyCode == 39) right = true;
if (e.keyCode == 40) down = true;
if (e.keyCode == 17) shoot = true;
if (e.keyCode == 32) drop = true;
e.preventDefault();
}
document.onkeyup = function (e) {
if (e.keyCode == 37) left = false;
if (e.keyCode == 38) up = false;
if (e.keyCode == 39) right = false;
if (e.keyCode == 40) down = false;
if (e.keyCode == 17) shoot = false;
if (e.keyCode == 32) drop = false;
e.preventDefault();
}
function draw() {
requestAnimationFrame(draw);
if (shoot) {
bullet = new Bullet(player.x - 3, player.y - 3, 6, 10)
bullets.push(bullet);
}
for (i = 0; i < bullets.length; i++) {
bullets[i].show();
bullets[i].move();
}
if (drop) {
bomb = new Bomb(player.x - 8, player.y + 50, 16, 1)
bombs.push(bomb);
}
for (i = 0; i < bombs.length; i++) {
bombs[i].show();
bombs[i].move();
}
}
requestAnimationFrame(draw);
Full code on remote server:
https://stacho163.000webhostapp.com
Is that a way to do it in my code or i have to change the way the buttons work?
If there is a solution without jQuery, that would be great.
e: checked the first tip, but after creating the first single bullet/bomb it's working as it was before.
Thank you for your tips :)
You should set some sort of wait variable, that indicates that the key is currently pressed, and no processing needs to take place:
let dropping = false;
// indicates that the bomb is dropping right now. Do not drop a new bomb
//...
if (e.keyCode == 32) {
drop = true;
dropping = true;
setTimeout(function () { dropping = false; }, 1000);
// if 1 second has passed, reset the dropping variable, to allow another bomb to drop
}
//...
if (drop && !dropping) {
bomb = new Bomb(player.x - 8, player.y + 50, 16, 1)
bombs.push(bomb);
}
This way, your bomb will only drop once every 1 second. Rinse and repeat :)

Event when space is pressing, only one time

I have some issues: I have this : (in a function..)
var space = 0;
setInterval(space, 20);
var keys = {}
$(document).keydown(function(e) {
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
delete keys[e.keyCode];
});
function space() {
for (var direction in keys) {
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
space++;
console.log(space);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?
What seems to be happening is that since it's running every 20 ms, as you hold down the space bar the space function is continuously incrementing the count. I added a flag to prevent another execution until the key is released and it works fine. Really you should just use the keypress event and check there if the keyCode === 32 to track your count. Fewer events will be fired. If you want to see what was happening you can comment out the flag and check the console.
var spaceCount = 0;
var running = false;
var keys = {}
$(document).keydown(function(e) {
console.log("keycode", e.keyCode);
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
console.log("keyup")
delete keys[e.keyCode];
running = false;
});
function space() {
if(running) return;
for (var direction in keys) {
running = true;
console.log(direction);
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
spaceCount++;
console.log("count: " + spaceCount);
console.log(keys);
}
}
}
setInterval(space, 20);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I hope that will be helpful:
var space = 0;
var keys = {};
var keys2 = {};
$(document).keydown(function(e) {
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
keys[e.keyCode] = false;
});
setInterval(function(){spacing()}, 20);
function spacing() {
if (keys[32] && !keys2[32])
{
space++;
keys2[32] = true;
}
else if(!keys[32])
{
keys2[32] = false;
}
console.log(space);
}

KeyDown doesn't continuously fire when pressed and hold

I have this Plunkr,
This contains a div, on which I bind a keydown event. On pressing right or left arrow, the div should start moving.
This works, in all browsers, but when the key is pressed and hold, the first keydown event is fired immediately (div once moves), and it waits for a time gap, and then it continues to move.
So this means the keydown event is once fired, then the browser waits to detect if there is a subsequent keyUp event as well, then after a short time (when there is no keyup), it continues to fires keydown events.
(to see the problem, focus on window, press right arrow and hold, div should move once 5px, then wait, and then again continue to move)
Question: Is there a way around, so I can just keep the key pressed, and div should immediately start moving, without waiting to detect subsequent keyup (once)?
$(function() {
$(window).keydown(function(e) {
console.log(e.keyCode)
if (e.keyCode == 39)
move(5, 'left', $('.mover'))
else if (e.keyCode == 37)
move(-5, 'left', $('.mover'))
})
})
function move(offset, direction, target) {
console.log($(target))
$(target).css(direction, (parseInt($(target).css(direction)) + offset) + 'px')
}
.mover {
height: 50px;
width: 50px;
display: inline-block;
background: black;
position: absolute;
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='mover'></div>
I would suggest something on a timeout, like this
http://codepen.io/kevrowe/pen/qEgGVO
$(function() {
var direction,
movingTimeout = -1;
$(window).on('keydown', function(e) {
if (e.keyCode == 39) {
direction = 'right';
} else if (e.keyCode == 37) {
direction = 'left';
}
startMoving(direction);
});
function stopMoving() {
clearTimeout(movingTimeout);
movingTimeout = -1;
}
function startMoving(direction) {
if (movingTimeout === -1) {
loop(direction);
}
}
function loop(direction) {
move(direction === 'left' ? -5 : 5, $('.mover'));
movingTimeout = setTimeout(loop, 10, direction);
}
function move(offset, $target) {
$target.css('left', (parseInt($target.css('left')) + offset) + 'px')
}
$(window).on('keyup', function(e) {
stopMoving();
});
})
When keydown event occurs on the key you want to track, then store this information in a mapping or a flag somewhere.
When keyup event occurs, then clear the flag for the given key.
Then, on a timer, you could poll the state of the key mapping, and move the object for whatever key direction is being pressed.
Possibly there is a better solution then polling, but I don't know of a way to test if a key is down other than polling.
On keyup, would also need to check if needed to interrupt moving the object.
One solution would be to just continuously run the move function in a loop until keyup happens
if (e.keyCode == 39){
var stop = setInterval(function(){
move(5, 'left', $('.mover'))
}, 25);
window.on("keyup", function(){
//stop the loop
clearInterval(stop);
//and remove the keyup listener
window.off("keyup", arguments.callee);
})
} else if //etc...
For those that might interest, here is another approach to handle bi-directional movement. Ex: up + right keys = "North East" direction :
const FPS = 60;
const STEP = 5;
const UP_KEY = 90; // Z
const DOWN_KEY = 83; // S
const LEFT_KEY = 81; // Q
const RIGHT_KEY = 68; // D
const pressedKeys = [];
let movingTimeout = null;
function handleKeyDown(e) {
pressedKeys[e.keyCode] = true;
switch(e.keyCode) {
case DOWN_KEY:
case LEFT_KEY:
case RIGHT_KEY:
case UP_KEY:
e.preventDefault();
startMoving();
}
}
function handleKeyUp(e) {
pressedKeys[e.keyCode] = false;
const shouldStop = !pressedKeys[UP_KEY]
&& !pressedKeys[DOWN_KEY]
&& !pressedKeys[LEFT_KEY]
&& !pressedKeys[RIGHT_KEY]
;
if(shouldStop) {
stopMoving();
}
}
function startMoving() {
if(!movingTimeout){
loop();
}
}
function stopMoving() {
clearTimeout(movingTimeout);
movingTimeout = null;
}
function loop() {
const x = pressedKeys[RIGHT_KEY] ? STEP
: pressedKeys[LEFT_KEY] ? -STEP : 0;
const y = pressedKeys[DOWN_KEY] ? STEP
: pressedKeys[UP_KEY] ? -STEP : 0;
move(x, y);
movingTimeout = setTimeout(loop, 1000 / FPS);
}
function move(x, y) {
// Implement you own logic here for positioning / handling collisions
// Ex: store.dispatch({ type: "MOVE_PLAYER", x, y });
console.log(`Moving ${x} ${y} !`);
}
window.addEventListener('keydown', e => handleKeyDown(e));
window.addEventListener('keyup', e => handleKeyUp(e));
Hope this helps.
Cheers !
pure javascript
<input id="some" type="text">
var input=document.getElementById("some");
input.addEventListener("keydown",function(e){
if (e.which == 40) {
var stop = setInterval(function(){
console.log("ss:");
}, 60);
window.addEventListener("keyup", function(){
//stop the loop
clearInterval(stop);
//and remove the keyup listener
window.removeEventListener("keyup", arguments.callee);
})
}
})

Horizontal movement with Javascript

I feel like a complete klutz, I had this working and then I accidentally forgot to save it! I'm an idiot. I've spent the last day trying to recreate what I had but I can't do it. Basically (from my last save) I had this:
function canvasMove(e) {
if(!e) var e = window.event;
var downcheck;
var upcheck;
var leftcheck;
var rightcheck;
if(e.keyCode == '38') {
if(up + down == 0) downcheck = false;
else downcheck = true;
e.preventDefault();
}
if(e.keyCode == '40') {
if(up + down > HEIGHT - 110) upcheck = false;
else upcheck = true;
e.preventDefault();
}
if(e.keyCode == '37') {
if(left + right == 0) rightcheck = false;
else rightcheck = true;
e.preventDefault();
}
if(e.keyCode == "39") {
if(left + right > WIDTH - 110) leftcheck = false;
else leftcheck = true;
e.preventDefault();
}
if(leftcheck == true) { left += 10; counting() };
if(rightcheck == true) { right -= 10; counting() };
if(upcheck == true) { up += 10; counting(true) };
if(downcheck == true) { down -= 10; counting(true) };
}
The problem of course being that Javascrpt doesn't support the ability to check if two keys are being pressed at the same time. What I want to accomplish is when the user pressed up and left they'll move diagonally. Ignore the "counting" function, it's just to keep track of how much the user has moved.
I managed to accomplish this with just else and if statements, no less! So I was wondering if you guys could give it a shot. The first if statement in each key if statement is so the user can't leave the canvas box. Then I have a function that moves the user by redrawing the canvas.
function redraw() {
clear(draw);
draw.fillStyle = 'rgba(0,0,0,0.5)';
draw.fillRect(left + right, up + down, '100', '100');
}
The "clear" function is just a simple function that clears the entire canvas. This is all controlled by an init function that looks like this:
function init() {
canvas = document.getElementById('game');
HEIGHT = canvas.height;
WIDTH = canvas.width;
draw = canvas.getContext('2d');
setInterval(redraw, 30);
document.onkeydown = canvasMove;
}
Your -check flags need to be global variables rather than function-scoped variables, otherwise they will never stay set between keydown events (handling only one key at a time). You also need a keyup event handler that will unset the correct flag when a key is released.

Categories

Resources