Touch control for html5 game - javascript

I've been working on a simple html5 canvas game, and I'm trying to add touch controls for devices as well as keyboard input for desktops etc.
The keyboard controls are perfect: space bar is tapped to jump, and held for a longer jump.
I've added event listeners for touch control, which emulate the single tap of the spacebar, but I can't figure out how to recreate holding the space bar for longer jumps with the touch control. My keyboard code looks like this:
// jump if not currently jumping or falling
if (KEY_STATUS.space && player.dy === 0 && !player.isJumping) {
player.isJumping = true;
assetLoader.sounds.jump.play();
player.dy = player.jumpDy;
jumpCounter = 12;
}
// jump higher if the space bar is continually pressed
if (KEY_STATUS.space && jumpCounter) {
player.dy = player.jumpDy;
assetLoader.sounds.jump.play();
}
jumpCounter = Math.max(jumpCounter-1, 0);
this.advance();
And that gets tracked with this code:
var KEY_CODES = {
32: 'space'
};
var KEY_STATUS = {};
for (var code in KEY_CODES) {
if (KEY_CODES.hasOwnProperty(code)) {
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;
}
};
My new event listeners for touch screen devices looks like this:
document.addEventListener("touchstart", touchHandler);
document.addEventListener("touchhold", touchHandler);
document.addEventListener("touchend", touchHandler);
And then I have this function, which is more or less identical to the function for keyboard input, only 'e.touches' is referenced, rather than 'KEY_STATUS':
function touchHandler(e) {
if(e.touches && player.dy === 0 && !player.isJumping) {
player.isJumping = true;
assetLoader.sounds.jump.play();
player.dy = player.jumpDy;
jumpCounter = 12;
e.preventDefault();
}
}
That function enables the little jump. If I include this 'if' statement, it enables multiple jumps:
if (e.touches && jumpCounter) {
player.dy = player.jumpDy;
assetLoader.sounds.jump.play();
}
...rather than enabling the player to perform the longer jump. Essentially, the player could tap to fly throughout the game, which I don't want! Is there a way to specify within the 'touchHandler()' function which kind of jump is being made ie. is the screen being tapped or held? Or would I need to write a separate function for that?
Thanks in advance.

Related

Javascript Play/Pause button Keyboard event

I'm still working on a music player, mouse controls have been assigned, but I'm having little trouble with keyboard events on the PLAY/PAUSE button.
So far, I got the user to be able to "click" the PLAY button by pressing SPACEBAR. What happens is that the PLAY button is being hidden and replaced by the PAUSE button.
Which I want now is getting the user to be able to press the SPACEBAR again so it "clicks" PAUSE, and therefore shows PLAY again.
Here is what I have :
html
<div>
</div>
script
<script>
/* mouse */
$('#play').on('click', function(event) {
console.log('play click clicked');
//currentPlayingTrack.play();
$('#pause').show();
$('#play').hide();
$('#pause').on('click', function(event) {
//currentPlayingTrack.pause();
$('#pause').hide();
$('#play').show();
});
/* keyboard */
var play = document.getElementById("play");
var pause = document.getElementById("pause");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
else if(e.keyCode == 32) {
pause.click();
}
};
</script>
What am I missing ?
the mistake is here:
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
} else if(e.keyCode == 32) {
pause.click();
}
};
the second condition cannot be executed because everytime the keyCode is 32 it's goes only in the first conditions.
You can declare a variable "isPlaying" that indicate you if the player is playing.
var isPlaying = false;
document.onkeydown = function (e) {
if (e.keyCode == 32) {
if (isPlaying) {
pause.click();
} else {
play.click();
}
isPlaying = !isPlaying; // if true equal false, if false equal true
}
};
the first mistake is that you arent closing all brackets,the second is this part of code:
if (e.keyCode == 32) {
play.click();
}
else if(e.keyCode == 32) {
pause.click();
}
i suggest to use a variable for check if the button play is being pressed or not:
var ispaused = true;
var play = document.getElementById("play");
var pause = document.getElementById("pause");
$('#play').on('click', function(event) {
ispaused = false;
console.log('play click clicked');
//currentPlayingTrack.play();
$('#pause').show();
$('#play').hide();
/* keyboard */
});
$('#pause').on('click', function(event) {
ispaused = true;
//currentPlayingTrack.pause();
$('#pause').hide();
$('#play').show();
});
document.onkeydown = function (e) {
if (e.keyCode == 32) {
if(ispaused == true ){
play.click();
}else{
pause.click();
}
}
};
fiddle
It works. you double check space keyCode when you space anytime and the first condition would be true every single time.
Second, you need to use $bla instead for $("#blablabla") .It runs almost 600 line Code with find object you select everytime.So don't be let duplicate work.
Final,$() is lik $(doucument).ready().It's all done when rendered it's done and DOM it's OK.THAT IS!
** code **
$(function () {
let $play = $("#play");
let $pause = $("#pause");
$play.on('click', function (event) {
console.log('play click clicked');
//currentPlayingTrack.play();
$pause.show();
$play.hide();
});
$pause.on('click', function (event) {
//currentPlayingTrack.pause();
$pause.hide();
$play.show();
});
/* keyboard */
document.onkeydown = function (e) {
if (e.keyCode == 32) {
toggle = !toggle;
$play.trigger("click");
}
else if (e.keyCode == 32) {
toggle = !toggle;
$pause.trigger("click");
}
};
});
Seems like you're missing a bit more knowledge of js which will come with time :) Here's a codepen on how I'd accomplish this.
http://codepen.io/smplejohn/pen/zNVbRb
Play
Pause
$('.playpause').click(function(){
$('.playpause').toggle();
return false;
});
document.onkeydown = function (e) {
if (e.keyCode == 32){
$('.playpause').toggle();
}
};

JavaScript or jquery trigger left arrow key press event (Simulate arrow key press)

I am trying to simulate the left and the right arrow key press in a text area within a rad grid control (Telerik).
I have a bug that is specific to the browser Firefox where the tab event(got this part fixed) and the arrow keys wont work. Every other browser works fine.
So as a workaround i want to simulate the arrow keys using JavaScript or jquery.
Below is what i have working with the tab event fix included. In addition to this I check if the key code 37 (this is the left arrow key) is pressed. At this point i want to simulate the left arrow press in the text area.
$(document).on('keydown', function (event) {
if (event.keyCode == 9) { //tab pressed
event.preventDefault(); // stops default action
}
});
$('body').keyup(function (e) {
var code = e.keyCode || e.which;
//Left arrow key press
if (code == '37')
{
moveLeft();// This does not trigger the left arrow event
}
//Tab button pressed
if (code == '9') {
//shift was down when tab was pressed focus -1
if (e.shiftKey && code == 9) {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) - 1).focus();
}
//tab was pressed focus +1
else {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) + 1).focus();
}
}
});
Any help on this issue would be appreciated
I got this working by moving the cursor back one space, below is the code I used to simulate the left arrow key press.
Note - To simulate right the key code is 39 and set the myval property to -1.
$('body').keydown(function (e) {
var code = e.keyCode || e.which; //Find the key pressed
if (code == '37') {
e.preventDefault(); // stop default action
var elementId = e.target.id;// get id of input text area
var el = document.getElementById(elementId),
myval = 1 // set mouse cursor to move back one space
cur_pos = 0;
if (el.selectionStart) {
cur_pos = el.selectionStart;
}
else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r != null) {
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
cur_pos = rc.text.length;
}
}
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(cur_pos - myval, cur_pos - myval);
}
else if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', cur_pos - myval);
range.moveStart('character', cur_pos - myval);
range.select();
}
}

Respond to 2 Keypresses at same time

I'm practicing moving around objects when a user presses an arrow key. I've got it so when they press right it moved an object to the right and when they press up it moves it up. However, my function is only able to record 1 of these keypresses at once, so they can't move diagonally:
document.onkeydown = function(e){
if (e.which == 39){ // Move Right
var position = $("#ball1").position();
$("#ball1").offset({left:position.left+2});
}
if (e.which == 38){ // Move Up
var position = $("#ball1").position();
$("#ball1").offset({top:position.top-2});
}
};
Is there a way to respond to both key presses at the same time?
You have to detect both keydown and keyup
var key = {};
document.onkeydown = function(e){
if (e.which == 39 || e.which == 38){ // Move Right
key[e.which] = true;
if (key[39]) {
var position = $("#ball1").position();
$("#ball1").offset({left:position.left+2});
}
if (key[38]) {
var position = $("#ball1").position();
$("#ball1").offset({top:position.top-2});
}
}
};
document.onkeyup = function(e){
if (key[e.which])
delete key[e.which];
};

iOS touches HTML5

I'm trying to make a HTML5 game that I've built for web compatible with iOS touches instead of using the left and right keys on the keyboard. What is the best way to access touches in the same way as onkeyup?
Code for the onkeyup:
document.onkeyup = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = false;
} else if (key == 39) {
dir = "right";
player.isMovingRight = false;
}
};

How can I get auto-repeated keydown events in Firefox when arrow keys are held down?

I've got several editable divs. I want to jump through them by pressing arrow keys (38 and 40).
Firefox 3 on Mac OS and Linux won't repeat the events on holding the key. Obviously only keypress events are supported for repetition. As the keys 38 and 40 are only supported on keydown I'm kind of stuck.
Yes, you're kind of stuck. You could emulate the behaviour you want by using timers until you receive the corresponding keyup, but this obviously won't use the user's computer's keyboard repeat settings.
The following code uses the above method. The code you want to handle keydown events (both real and simulated) should go in handleKeyDown:
var keyDownTimers = {};
var keyIsDown = {};
var firstKeyRepeatDelay = 1000;
var keyRepeatInterval = 100;
function handleKeyDown(keyCode) {
if (keyCode == 38) {
alert("Up");
}
}
function simpleKeyDown(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
handleKeyDown(keyCode);
}
document.onkeydown = function(evt) {
var timer, fireKeyDown;
evt = evt || window.event;
var keyCode = evt.keyCode;
if ( keyIsDown[keyCode] ) {
// Key is already down, so repeating key events are supported by the browser
timer = keyDownTimers[keyCode];
if (timer) {
window.clearTimeout(timer);
}
keyIsDown[keyCode] = true;
handleKeyDown(keyCode);
// No need for the complicated stuff, so remove it
document.onkeydown = simpleKeyDown;
document.onkeyup = null;
} else {
// Key is not down, so set up timer
fireKeyDown = function() {
// Set up next keydown timer
keyDownTimers[keyCode] = window.setTimeout(fireKeyDown, keyRepeatInterval);
handleKeyDown(keyCode);
};
keyDownTimers[keyCode] = window.setTimeout(fireKeyDown, firstKeyRepeatDelay);
keyIsDown[keyCode] = true;
}
};
document.onkeyup = function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
var timer = keyDownTimers[keyCode];
if (timer) {
window.clearTimeout(timer);
}
keyIsDown[keyCode] = false;
};
You can use keypress and check the e.keyCode == 38,40 instead of e.which or e.charCode
This is consistent across Mac and Win.
$('#test').bind($.browser.mozilla ? 'keypress' : 'keyup', function(e) {
if ( (e.which || e.keyCode) == 40 ) { /* doSometing() */ }
});
See JavaScript Madness: Keyboard Events (3.2. Values Returned on Character Events)
and event.keyCode on MDC.

Categories