I know there are many solutions with this type of question but somehow they are very complex.
I wanted to know what happens once a function is called. For example, in my sample code, when I call keyboardHandler() once, the eventHandler will add the keyPressed() and keyReleased() functions to the keydown and keyup events. But since they are not global functions (but defined inside another function), will I be able to access them outside, in the global area, when a key is pressed?
If yes, does that mean a function once called is somewhat stored in the memory?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var leftPressed = false;
var upPressed = false;
var rightPressed = false;
var downPressed = false;
function keyboardHandler() {
document.addEventListener("keydown", keyPressed);
document.addEventListener("keyup", keyReleased);
function keyPressed(e) {
switch(e.keyCode) {
case 37:
leftPressed = true;
break;
case 38:
upPressed = true;
break;
case 39:
rightPressed = true;
break;
case 40:
downPressed = true;
break;
}
}
function keyReleased(e) {
switch(e.keyCode) {
case 37:
leftPressed = false;
break;
case 38:
upPressed = false;
break;
case 39:
rightPressed = false;
break;
case 40:
downPressed = false;
break;
}
}
}
Related
I have function for stop and start the setInterval with key .
it's starts with S key and stops with Z key .
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
// code...
},10);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}
So how can i set only Z key for start and stop the SetInterval ??
for example i press Z key and it starts then i press Z key again and it stops !
anyone can help me ?
Modify your code like below,
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 90:
if(refreshIntervalId) {
stop();
}
else {
start();
}
break;
}
}
Check if refreshIntervalId is a truthy value. If it is then stop the interval else start it.
var boolStart = false;
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
if(!boolStart){
start();
}else{
stop();
}
break;
}
}
function start() {
stop();
boolStart = true;
..
}
function stop() {
boolStart = false;
....
}
EDIT 1:
You can do in this way also.
var boolStart = false;
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
//;
boolStart = !boolStart;
if (!boolStart) {
start();
} else {
stop();
}
break;
}
}
I'm creating a canvas game for fun, and I'm trying to re-factor some of my multiple else if statements to use object lookup tables instead.
This is my current code for assigning variable values on keydown:
function keyDown(e) {
keypressed = true;
if (e.keyCode == 39 || e.keyCode == 68) {rightKey = true; }
else if (e.keyCode == 37 || e.keyCode == 65) {leftKey = true;}
else if (e.keyCode == 38 || e.keyCode == 87) {upKey = true; }
else if (e.keyCode == 40 || e.keyCode == 83) {downKey = true; }
else if (e.keyCode == 80) { isPaused = !isPaused; document.body.classList.toggle('pause'); }
if (e.keyCode === 69) { startHit(); }
}
I want to assign both wsad keys and the arrow keys to do the same thing, thus the use of || in the if conditions.
I read that using an object literal lookup table is a faster way to achieve this and this is my attempt:
var codes = {
39 : function() {
return rightKey = true;
},
37 : function() {
return leftKey = true;
},
38 : function() {
return upKey = true;
},
40 : function() {
return downKey = true;
},
80 : function() {
isPaued = !isPaused;
document.body.classList.toggle('pause');
},
69 : startHit
}
codes[68] = codes[39];
codes[65] = codes[37];
codes[87] = codes[38];
codes[83] = codes[40];
function keyDown(e) {
keypressed = true;
codes[e.keyCode]();
}
This works just fine, but I'm not sure the assignment of the bottom keys is the best way to do this? I can't obviously use the || operator in the left hand assignment, so would there be a cleaner way to do this or should I just stick with the else ifs?
Also, I know I could use a switch statement, but I feel like it would look similar to the way I've done above.
Any advice would be great. Thanks.
Why not use a switch statement?
function keyDown(e) {
keypressed = true;
switch (e.keyCode) {
case 39:
case 68:
rightKey = true;
break;
case 37:
case 65:
leftKey = true;
break;
case 38:
case 87:
upKey = true;
break;
case 40:
case 83:
downKey = true;
break;
case 80:
isPaused = !isPaused;
document.body.classList.toggle('pause');
break;
case 69:
startHit();
}
}
what about this?
var codes = function (){
function rightKey(){
rightKey = true;
}
function leftKey() {
leftKey = true;
}
return {
39 : rightKey,
37 : leftKey,
'...': '...',
68 : rightKey,
65 : leftKey
}}()
What I want to do is when I press on right key from keyboard return 100 and when I press again return 200 then 300 and so on...
function looptest() {
for (i = 100; i < 1000; i+=100) {
result+=i;
}
}
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
console.log(looptest());
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
This is my code and it returns every time 100, what's wrong in my code?
just do simply something like
var count= 100;
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
console.log(count)
count=count+100;
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
or if you want to use looptest() then change your function like below
count=0;
function looptest() {
count=count+100;
}
Assign K=0 in global space
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
K+=100
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
This code will add 100 to i everytime you press the right key of your keyboard.
var i = 0;
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
i = i+100;
console.log(i);
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
var result = 0;
function looptest() {
for (i = 100; i < 1000; i+=100) {
result =(result + i);
}
}
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
console.log(looptest());
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
declare result globally
and while adding it is concating so please add them inside ()
Space Invader game: I want to control the 'base gun' (move it left and right and fire missiles at the invaders. So I need a keypress or (keydown?) event to change a variable (x coordinate) and a key press event to fire a missile.
Can anyone show me how the keypress event is detected and the variable is changed?
document.onkeydown = function(e) {
var key = e.keyCode;
if (key===37) {//left arrow pressed
} else if (key===39) {//right arrow pressed
}
}
Like this?
document.onkeydown = checkKey;
var xCoord = 100;
function checkKey(e) {
e = e || window.event;
switch (e.keyCode) {
case 37 : // left
xCoord -= 5;
break;
case 39 : // right
xCoord += 5;
break;
}
}
Exciting fiddle: http://jsfiddle.net/u5eJp/
Couple things I would like to add to the other answers:
1) Use constants to make it easier on yourself
2) There is no way to check if a key is currently pressed in javascript, so you should keep track of what is currently pressed as well
var pressed = {
up: false,
down: false,
left: false,
right: false
};
var LEFT_ARROW = 37;
var UP_ARROW = 38;
var RIGHT_ARROW = 39;
var DOWN_ARROW = 40;
document.onkeydown = function (e) {
e = e || window.event;
switch (e.keyCode) {
case LEFT_ARROW:
pressed.left = true;
break;
case UP_ARROW:
pressed.up = true;
break;
case RIGHT_ARROW:
pressed.right = true;
break;
case DOWN_ARROW:
pressed.down = true;
break;
default:
break;
}
}
//update position separately
function updatePos() {
if (pressed.up) { //change y up }
if (pressed.down) { //change y down }
if (pressed.left) { //change x left }
if (pressed.right) { //change x right }
}
Hope this helps, and good luck!
I have to make a game for school with html5 canvas Javascript.
I am new to javascript and still learning but i really need some help with this issue that i have and would appreciate it if someone could help me out. I tried several things but nothing seems to work and im at a loss.
So this is the code for the player object. It can move from left to right.
Now the problem is that it leaves the canvas. I want it to stay in the canvas on the x axes.
// Things to do when keys are down
function onKeyDown(event) {
// prevent arrow keys from scrolling the page
if (event.keyCode >= 37 && event.keyCode <= 39) event.preventDefault();
switch (event.keyCode) {
case 37:
player.vx = -1;
player.image = player.imgLeft;
break; // left key
// case 38: player.vy = -1; break; // up key
case 39:
player.vx = 1;
player.image = player.imgRight;
break; // right key
}
}
// Things to do when keys are up
function onKeyUp(event) {
switch (event.keyCode) {
case 37:
case 39:
player.vx = 0;
player.image = player.original;
break; // left or right key released
// case 38: player.vy = 0; break; // up or down key released
}
}
This is what i got so far....
if ((player.x >= 800) && (player.x <= 0)) {
} else {
}
You could consider adding two functions to check that you're within bounds.
(Essentially the same as your code, albeit with my true condition returned in what would be your else statement.)
// returns true if param is in range [0..799]
function isInXrange(intPos)
{
if ((intPos>=0) && (intPos<800))
return true;
else
return false;
}
// returns true if param is in range [0..599]
function isInYrange(intPos)
{
if ((intPos>=0) && (intPos<600))
return true;
else
return false;
}
You could then add a function to move the player and another to handle colliding with the walls/wandering out of bounds
function movePlayer()
{
if (isInXRange(player.x))
player.x += player.vx;
if (isInXRange(player.y))
player.y += player.vy;
}
function handleOutOfBounds()
{
if (isInXRange(player.x) == false)
{
// do something;
}
if (isInYRange(player.y) == false)
{
// do something else
}
}
Basically just test to see if x + width (optional: + velocity) > canvas.width and the same for height.