I'm new here and also new with web coding. So i am trying to make a function to move my game character when a button is pressed. When button is pressed down a boolean value changes to "true" and the character moves. I was trying to do it somehow like this. Can someone light me up what is the best way to make this work? I need also to do this for all the rest buttons (a,s,d,arrows).
var wButton = false;
function newfunction()
document.querySelector('#keyButtonW').addEventListener('mousedown', function(event) {
keyButtonPressed("wButton", true);
});
document.querySelector('#keyButtonW').addEventListener('mouseup', function(event) {
keyButtonPressed("wButton", false);
});
document.querySelector('#keyButtonW').addEventListener('mouseleave', function(event) {
keyButtonPressed("wButton", false);
});
Assuming translate is a method to move your char, maybe you should make a big maskArray :
var keyboard = [];
function keyDown(e)
{
var key = event.keyCode || event.which;
keyboard[key] = true;
}
function keyUp(e)
{
var key = event.keyCode || event.which;
delete keyboard[key];
}
function keyAction() {
for (i in keyboard)
{
if (keyboard[i] == true)
{
switch(eval(i))
{
case 90: //Z
character.translateY(-1);
break;
case 83: //S
character.translateY(1);
break;
case 81: //Q
character.translateX(-1);
break;
case 68: //D
character.translateX(1);
break;
}
}
}
return false;
}
document.addEventListener("keydown", keyDown, false);
document.addEventListener("keyup", keyUp, false);
Simply put keyAction() inside your main loop / rendering loop.
The value of this is to not make lags happen when you hit a button, and help with multiple pressing management =)
EDIT
To get the key numbers, simply put a console.log(key) at the end of keyDown().
Related
I have a code like this:
$("textarea").on('keydown', function(e){
if(e.ctrlKey){ // Ctrl is pressed
switch (e.which) {
case 66: // "B" button on the keyboard
alert("it is bold");
break;
case 73: // "I" button on the keyboard
alert("it is italic");
break;
}
e.preventDefault();
return false;
}
});
The above code handles Ctrl + B and Ctrl + I on keydown of textarea. Also there is two lines of code which stop every things:
e.preventDefault();
return false;
This ^ codes stops the action of any button. For example Ctrl + S is deactivate now ..! What I need is to define if that switch() function matches a case, then run those two lines, else don't run those two lines. How can I do that?
Try like this if key press other then Ctrl+B or Ctrl+I then it won't do anything.
$("textarea").on('keydown', function(e){
if(e.ctrlKey){ // Ctrl is pressed
var codes= [66,73];
var a = codes.indexOf(e.which);
if(a > 0){
return false;
}else{
// your stuff
}
}
});
Use the default case!
switch (e.which) {
case 66: // "B" button on the keyboard
alert("it is bold");
break;
case 73: // "I" button on the keyboard
alert("it is italic");
break;
default: // everything else
return; // without preventing the default action
}
e.preventDefault();
return false;
I am developing a game where you must press the left and right arrow keys alternatively to make the character move, the faster you do it, the quicker he runs. I have however ran into a problem whereby the key is being "held down" in a sense so no matter how quick you press the key it still manages to execute it multiple times.
So I am looking for a way to make the key only be pressed once per press rather than updating if you hold down the key.
here is the code for my key capturing and what it executes at the moment (Which is just an update of points and an update of the image used for the character.
KEY_CODES = {
37: 'left',
39: 'right',
40: 'down',
}
KEY_STATUS = {};
for (code in KEY_CODES) {
KEY_STATUS[KEY_CODES[code]] = false;
}
document.onkeydown = function (e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
}
document.onkeyup = function (e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
}
function move() {
movecounter++;
// Determine if the action is move action
if (KEY_STATUS.left || KEY_STATUS.right ||
KEY_STATUS.down || KEY_STATUS.up) {
// Redraw the canavs background images ready for the new ones to be placed ontop.
paintCanvas();
// to have diagonal movement.
if (KEY_STATUS.left) {
ctx.drawImage(imageStore.snowWalk, playerPosW, playerPosH);
snowStand = true;
score += 10;
} else if (KEY_STATUS.right) {
ctx.drawImage(imageStore.snowWalk, playerPosW, playerPosH);
score += 10;
} else if (KEY_STATUS.down) {
ctx.drawImage(imageStore.snowCrouch, playerPosW, playerPosH);
snowStand = false;
}
}
};
Hope you understand the problem I am facing, I have tried to explain it as best as I can here.
Thanks!
A simple solution would be to have a variable outside of the scope of the event listener that tells you if you're pressing the key for the first time:
var pressed = false;
Then, in the listener, toggle the state of that variable when the key is pressed:
.keydown(function() {
if (pressed) return;
pressed = true;
}
.keyup(function() {
pressed = false;
}
Please Help! I have spent a week to complete this game and this is the final huddle i have been stuck with for a couple of days now. I know some techy out there would probably take a glance and flick something in place. But I'm not very sophisticated with javascript and therefore need some help.
$(document).keydown(function(e){
// left arrow
if (e.keyCode == 37 && currentCell > 0) {
currentCell--;
ChangeCurrentCell();
return false;
}
// up arrow
if (e.keyCode == 38 && currentRow > 0) {
currentRow--;
ChangeCurrentCell();
return false;
}
// right arrow
if (e.keyCode == 39 && currentCell < MAX_CELL) {
currentCell++;
ChangeCurrentCell();
return false;
}
//down arrow
if (e.keyCode == 40 && currentRow < MAX_ROW) {
currentRow++;
ChangeCurrentCell();
return false;
}
// enter key
if (e.keyCode == 13) {
}
});
function ChangeCurrentCell()
{
document.getElementById(Boxes[currentRow + currentCell]).focus();
SimulateMouseOver(document.getElementById(Boxes[currentRow + currentCell]));
}
// function will trigger event of selecting current focus.
function selectElement()
{
}
$(document).ready(function(){
loadDivs()
// will give initial focus to top left element paving way for key navigation
ChangeCurrentCell();
// above gives first element in Boxes the focus when loading.
The div element will not focus despite getting it and calling the focus method, i have tried to trigger mousehover on the element with no luck. Please assist me, i put my masters thesis aside despite already being on a tight schedule to do this game which is a requirement for a job position. I have done whole the whole game logic and it all works well, if i send the code in as it is it will definitely be discarded because it doesnt meet the key navigation requirement ... i am desperate i will even pay if i need to -frustrated Student
Look at this
It's my solution for a test, maybe the same...maybe can help you :) If it is, please use it as a hint and don't copy all my code :D
Regards,
L.
You can bind to the document.keydown event to capture key strokes. Then you can use event.which (normalized by jQuery) to determine which key was pressed.
$(document).on("keydown", function (event) {
if (event.which === 37) {
//code for left arrow
} else if (event.which === 38) {
//code for up arrow
} else if (event.which === 39) {
//code for right arrow
} else if (event.which === 40) {
//code for down arrow
}
});
UPDATE
I just noticed you didn't tag your question with jQuery. To use native JS you'll have to change how you bind to the document.keydown event and how you determine the key that was pressed (different browser implementations store the info under different indexes of the event object).
to make it more convenient () not necessary:
`var LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, SPACE = 32;`
then bind to keydown, keypress doesn't catch arrow keys
and do something like this:
$(document).bind("keydown", function (e){
var which = e.which;
var navigationKeyWasPressed = which !== undefined && which >= 39 && which <= 40;
//do nothing if no significant key was pressed
if (!navigationKeyWasPressed ) {
return;
}
if ($(".selectedWithKey").length === 1){
switch (which) {
case LEFT:
//...
break;
case UP:
//...
break;
case RIGHT:
//...
break;
case DOWN:
//...
break;
case SPACE:
//turn card
break;
default: //non arrow pressed
//...
}
} else {
// if no card is selected, select one to start arrow navigation
$(".sponsor:first").addClass("selectedWithKey")
}
});
I cant figure out a good way to add buttons to a simple HTML5 game that I'm trying to adapt for another use.
Instead of using the arrow keys to control the player, I want to have an actual 'up, down, left, right' buttons that have to be clicked (or more accurately, touched on a mobile device).
Here is the input code I'm trying to adapt.
input.js:
(function() {
var pressedKeys = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
// Convert ASCII codes to letters
key = String.fromCharCode(code);
}
pressedKeys[key] = status;
}
document.addEventListener('submit', function(e){
console.log(e);
return false;
})
document.addEventListener('keydown', function(e) {
setKey(e, true);
});
document.addEventListener('keyup', function(e) {
setKey(e, false);
});
window.addEventListener('blur', function() {
pressedKeys = {};
});
window.input = {
isDown: function(key) {
return pressedKeys[key.toUpperCase()];
}
};
})();
And here is the code from app.js that references the 'isDown' function:
function handleInput(dt) {
if(input.isDown('DOWN') || input.isDown('s')) {
player.pos[1] += playerSpeed * dt;
}
if(input.isDown('UP') || input.isDown('w')) {
player.pos[1] -= playerSpeed * dt;
}
if(input.isDown('LEFT') || input.isDown('a')) {
player.pos[0] -= playerSpeed * dt;
}
if(input.isDown('RIGHT') || input.isDown('d')) {
player.pos[0] += playerSpeed * dt;
}
}
I'm totally new to trying to make HTML5 games so any suggestions on how to handle touch / click events would be great. Also, for the buttons themselves, is it better to use divs, forms, or something else?
Thanks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Edit / Update:
So I inserted this into my app.js:
$("#upButton").click(function(){
console.log("click");
player.pos[1] -= playerSpeed * dt;
})
It actually registers the click event but it generates a really weird and random number of "clicks" (anywhere from a couple doze to thousands). The particular code I'm adapting can be found at this repo: https://github.com/jlongster/canvas-game-bootstrap
This guy's game is pretty neat but it has a lot "advanced" things for a noob to HTML5 games like me.
if it is button that is always visible - create button in html and add click event.
if you need dynamic button on canvas - you can draw button, and on mouse click check if mouse click in button area and button is visible/active, then execute your action.
I have made a game using HTML5 Canvas Element, Javascript for facebook. You can visit it here, http://apps.facebook.com/snaqe_game. The problem I am facing is that when I press down arrow key, used for moving the snake implemented using Javascript onkeydown event, the game works normally but the scrollbars go up and down. I tried making an textbox(#activ) and setting focus to it. It worked but when I tried to make it invisible, it failed.
document.onkeydown = function(event) {
document.getElementById('activ').focus()
if (!allowPressKeys) {
return null;
}
var keyCode;
if(event == null) {
keyCode = window.event.keyCode;
} else {
keyCode = event.keyCode;
}
switch(keyCode) {
case 37:
if (direction != "right") {
moveLeft();
}
break;
case 38:
if (direction != "down") {
moveUp();
}
break;
case 39:
if (direction != "left") {
moveRight();
}
break;
case 40:
if (direction != "up") {
moveDown();
}
break;
default:
break;
}
}
At the end of your document.onkeydown function (after line 197 in snake.js), add
if (event.preventDefault) { event.preventDefault(); }
if (event.stopPropagation) { event.stopPropagation(); }
return false;
This prevents the browser from responding to the event, beyond executing your function.
You may also need to replace return null; on line 161 with these three lines.
event.stopPropagation in the MDN Docs
event.preventDefault in the MDN Docs
Early Event Handlers: Prevent Default at QuirksMode