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.
Related
I want to implement a canvas minesweeper game using plain javascript. I use 2D array for my grid. For the game, I need to detect right and left mouse clicks, each of which will do different things. My research directed me towards mousedown, mouseup, contextmenu, however, my code does not seem to work, as for the right click it does the functions for both right and left click,because the mouseup event gets triggered for the right click as well. Can anyone help me understand how to distinguish between the two? I ran into examples of event.which, where left click is event.which === 0, and the right click is event.which === 2, but that works only for buttons, as far as I understood.
Here is the code.
canvas.addEventListener('mouseup', function(evt) {
let x1 = Math.floor(evt.offsetX/(canvas.height/rows));
let y1 = Math.floor(evt.offsetY/(canvas.width/cols));
draw (y1, x1); //this is my drawing functions (draws the numbers, bombs)
}, false);
canvas.addEventListener('contextmenu', function(evt) {
let j = Math.floor(evt.offsetX/(canvas.height/rows));
let i = Math.floor(evt.offsetY/(canvas.width/cols));
ctx.drawImage(flagpic, j*widthCell+5, i*widthCell+2, widthCell-9,
widthCell-5); //draws the flag where right mouse clicked
}, false);
Use click event for left click:
canvas.addEventListener('click', function(evt) { // No right click
And use contextmenu for right click: (Right click from keyboard context menu, also allowing you mouse right click)
canvas.addEventListener('contextmenu', function(evt) { // Right click
You need to call evt.preventDefault() as well for preventing the default action.
For your context, if you wanted to use mousedown or mouseup events, then you can use event.button to detect the clicked button was left:
canvas.addEventListener('mousedown', function(evt) {
if(evt.button == 0) {
// left click
}
Here's the button click values:
left button=0,
middle button=1 (if present),
right button=2
You can look on the example shown in the following link for greater details:
MouseEvent.button
<script>
var whichButton = function (e) {
// Handle different event models
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left button clicked.');
break;
case 1:
console.log('Middle button clicked.');
break;
case 2:
console.log('Right button clicked.');
break;
default:
console.log('Unexpected code: ' + btnCode);
}
}
}
</script>
<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">
Click with mouse...
</button>
Try this might work for you
document.getElementById("mydiv").onmousedown = function(event) {
myfns(event)
};
var myfns = function(e) {
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left');
break;
case 1:
console.log('Middle');
break;
case 2:
console.log('Right');
break;
}
}
}
<div id="mydiv">Click with mouse...</div>
Reference
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
How can I switch case by scrolling, and make it so that whenever you scroll up it changes cases one direction, and when you scroll down it changes the cases in the other direction? I hope that makes sense.
Here is how I did what I want to do using hotkeys, but this time I don't want to use hotkeys, I want to use the scrolling feature (I don't mean clicking on the scroll)
document.addEventListener('keydown', function (e) {
if (ws) {
switch (e.keyCode) {
// T
case 84:
if (player.items[ITEM_TYPE.WINDMAIL]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.WINDMAIL].id + ",null]");
break;
// G
case 71:
e.stopPropagation();
if (player.items[ITEM_TYPE.SPIKES]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.SPIKES].id + ",null]");
break;
// Z
case 90:
e.stopPropagation();
if (player.items[ITEM_TYPE.EXTRAS]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.TURRET].id + ",null]");
break;
// F
case 70:
e.stopPropagation();
if (player.items[ITEM_TYPE.PITTRAP]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.PITTRAP].id + ",null]");
break;
}
}
}, true);
and that works fine, but I want to make it so that is possible to do the same thing but my scrolling instead!
Can you help?
You can listen for scroll events using addEventListener (documented here: https://developer.mozilla.org/en-US/docs/Web/Events/scroll)
for example
window.addEventListener('scroll', function(e) {
// do something
});
or to capture scroll events on smaller box within your ui
document.querySelector('.my-scrollable-box').addEventListener('scroll', function(e) {
// do something
});
once you've done that you can keep track of the last know scroll position to determine if they scrolled up or down
var last_known_scroll_position = 0;
window.addEventListener('scroll', function(e) {
if (window.scrollY > last_known_scroll_position) {
// the user scrolled down
} else {
// the user scrolled up
}
last_known_scroll_position = window.scrollY;
}
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;
}
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().
How to handle events while clicking button in samsung smart tv.if i design my form in scene means how i handle events please clear my doubt thanks in advance
In your index.html (main file) inside body tag define an a tag to make as 'anchor' for the key events:
Then in the Main.js file define the Main variable, a instance of TVKeyValue and Widget:
var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();
var Main =
{
};
Main.onLoad = function()
{
// Enable key event processing
this.enableKeys();
widgetAPI.sendReadyEvent();
};
Main.onUnload = function()
{
};
Main.enableKeys = function()
{
document.getElementById("anchor").focus();
};
Main.keyDown = function()
{
var keyCode = event.keyCode;
alert("Key pressed: " + keyCode);
switch(keyCode)
{
case tvKey.KEY_RETURN:
case tvKey.KEY_PANEL_RETURN:
alert("RETURN");
widgetAPI.sendReturnEvent();
break;
case tvKey.KEY_LEFT:
alert("LEFT");
break;
case tvKey.KEY_RIGHT:
alert("RIGHT");
break;
case tvKey.KEY_UP:
alert("UP");
break;
case tvKey.KEY_DOWN:
alert("DOWN");
break;
case tvKey.KEY_ENTER:
case tvKey.KEY_PANEL_ENTER:
alert("ENTER");
break;
default:
alert("Unhandled key");
break;
}
};
For more information consult this Tutorial (in Spanish): http://samsungstad.com/wiki/iniciando-con-smart-tv/programando-tu-primera-aplicacion-javascript/