Phaser - On key release? - javascript

Instead of detecting when a key is down, how do I detect if a key is released?

One option is to use onUpCallback. For example, in your create function add something like the following:
game.input.keyboard.onUpCallback = function (e) {
// These can be checked against Phaser.Keyboard.UP, for example.
console.log(e.keyCode);
};
I suppose you could also store whether the key is down in your update function, and then check on each iteration whether it's up, if you wanted to keep track of the amount of time the key were pressed down.
I'm not sure what sort of performance issues you would run into though, so I would probably start with onUpCallback.

Set a flag when the key is pressed. In the update loop check if the flag is set but the key is no longer down:
//... somewhere
var downFlag = false;
//... in update
if(yourkey.isDown){
downFlag = true;
}else{
if(downFlag){
downFlag = false;
//do something
}
}
..but start with what James says

Related

filtering data using .keypress - no plugins

I am trying to filter data using .keypress. My current approach is to capture the data from .keypress and pass to my filter function. I am successful in returning data that begins with a letter. So if I type A into my field it will return all cats that begin with A. I would like to narrow my search by typing in more letters and have it update each time. Is there a simple solution here? Here is the code
// retrieve data from key press
$("input").keypress(function (e) {
if (e.which !== 0 && e.charCode !== 0) {
var criteria = String.fromCharCode(e.keyCode|e.charCode);
}
$.getJSON('cats.json', function(cats) {
filterCats(cats, criteria);
});
});
// filter function
function filterCats(cats, criteria){
$.getJSON('cats.json', function(cats) {
//var filteredData = cats.filter(function(c){return c.breed.toUpperCase().indexOf(criteria.toUpperCase()) !== -1;});
var filteredData = cats.filter(function(c){return c.breed.toUpperCase().indexOf(criteria.toUpperCase()) === 0 ;});
renderData(filteredData);
});
}
As others mentioned, keyup is better because it fires after the key is released.
keydown
Fires when the user depresses a key. It repeats while the user keeps the key depressed.
keypress
Fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed.
keyup
Fires when the user releases a key, after the default action of that key has been performed.
Above from http://www.quirksmode.org/dom/events/keys.html
Also as the other answer states, running your code immediately after every key press could result in a lot of requests sent to the server.
Instead, try throttling it with a timeout.
var timeout, criteria;
$('input').keyup(function(e) {
clearTimeout(timeout);
timeout = setTimeout(function() {
criteria = this.value;
$.getJSON('cats.json', function(cats) {
filterCats(cats, criteria);
});
}.bind(this), 125);
});
As Andy pointed out in a comment, you need to use the value of the input, since you are currently looking at a single character upon each character entry. As Hossein Shahsahebi pointed out, keyup would be a more accurate event for what you desire to do. Also, do not forget about pasting, which should trigger the same logic.
I would like to add that I believe it is undesirable to do the searching upon each character entry. Imagine someone typing really quickly. You will have a lot of requests sent to the server. I would rather wait for a while before doing the search. When the event is triggered, store the current time in a variable and use setTimeout to wait for a second or so before calling the filterCats function. Whenever the event runs, override that variable to the current moment. When filterCats is executed, check whether the variable's value is old-enough. If not, return without filtering. If so, do the filtering. This will decrease server load due to this feature drastically.

Building A Timer in Javascript/jQuery

I'm currently working on a website which would work somewhat like this one:
http://www.keyhero.com/free-typing-test/
I'd like to build a timer which starts on the user's first key press, and ends when the user presses 'Enter'. When the timer ends, I'd want to get the resulting time and push it off to the backend (Django for me) where the WPM will be calculated. However, I have no idea how to get started on this, as I have little experience with jQuery and Javascript and haven't been able to find useful pages.
So my question is, how would I do this? I can post some of my Django files if a better picture of what I am asking is needed.
You manage the key events with .keypress() for know when the person click in the keyboard.
http://api.jquery.com/keypress/
And for key = "ENTER", you just need to validate if is equal to key 13
$('#id_tag').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
alert("Clicked on enter");
return false;
}
});
I see that post too, that are using keyup():
JQuery Event for user pressing enter in a textbox?
Well you're going to have to capture the keypress/keydown/keyup event in a jQuery event, then start a setInterval and have that function increment a counter variable of sorts. Then you just reference that variable whenever you want to see how many seconds have passed. A crude example would be:
window.secondsSinceTyped = 0;
$('#textbox').one('keypress', function (e) {
window.setInterval(function () {
window.secondsSinceTyped++;
}, 1000);
});
Then just reference the variable secondsSinceTyped whenever you want to check the time. Note that I used the jquery one binding which will only bind the event once so that every time you type it doesn't rebind the event.

save keydown in array and executes

im creating a simple 2d game, and I want save the keydown keys into array, and execute them inisde a loop, so the user can hold a key and make it look like the chartater is moving non stop.
i got a setInterval function that act like a game Timer, and it just loop it self all the time. i added a listener and an array to hold the key.
I checked the keys inside the array and it look fine but, the functions moveRight and moveLeft are not working for some reson.
here is the code:
this.keysPressed = new Array();
InitGameLoop: function () {
var that = this;
setInterval(function () {
$(document).keydown(function (e) {
var key = e.which;
that.keysPressed.push(key);
for (var i = 0; i < that.keysPressed.length; i++) {
if (that.keysPressed[i] == 38) {
that.moveRight(worldWidth, 10);
}
else if (that.keysPressed[i] == 37) {
that.moveLeft(10);
}
log(that.keysPressed, that.yPos);
that.keysPressed.pop();
}
});
}, 60);
my questions are:
what am i doing worng?
is this a good idea? (if not, please feel free to recommend me about another :) )
(sorry for my english)
Registering an eventhandler inside setInterval is always wrong. In your case, every 60 milliseconds you are creating an additional listener, and when you press a key, all of your listeners will fire. Also there is absolutely no need to store them in an array. Just register the listener once, and it will fire each time a key is pressed. If more than one keys are pressed, the listener will fire for each key individually.
$(document).keydown(function (e) {
var key = e.which;
console.log(key);
// call your according functions here
switch (key){
case 37: // moving left
// do stuff
// set a flag to indicate that you are moving left
moveleft = true;
break;
case 39: // moving right
// do stuff
// set a flag to indicate that you are moving right
moveright = true;
break;
}
});
Since you are catching the keydown, you should set flags. This way you can track which keys are pressed currently. On keyup, you are resetting these flags again (need another eventhandler for that).
Instead of storing the pressed keys in an array, make each key code activate a related var in a 'movement' array. e.g. when left is pressed, movement['left']=1. Use keyup to set it back to 0.
Have your loop check the array for each possible movement, and trigger the related functions in corelance to the active movements at that given moment.

How do I validate entry before input value is set?

I'm having a really strange problem. Here's my current Javascript:
jQuery('.highlightableTDCell input').keydown(function () {
var val = jQuery(this).val();
if (!GridView.prototype.validateStandardCellNumberFormat(val)) {
return false;
}
else return true;
});
When I use this, I can still get away with entering an illegal character, but no more than that. I'm really confused because I thought this would happen first.
Inside of the keydown event, the element.value has not yet been updated to account for the key that is currently being pressed. If you want to stop the key from hitting the input box, you need to interrogate the event.which and see if it is a key you want to allow or not.
The event is raised before the new content entered the input (letting you cancel the default behavior.)
You can use something like this, to get the new content:
$('.highlightableTDCell input').keypress(function(e){
var temp = this.value + String.fromCharCode(e.which)
return GridView.prototype.validateStandardCellNumberFormat(temp)
});
Note that it's not full proof. like when the user entered the new char in the middle of the input.
Validation should be done only on blur. With HTML5 it should be better, but not all browsers support it yet.
Tip: this.value == jQuery(this).val() There is no need to create jQuery object to get the value

Determining if key is pressed down in Javascript

I'm writing a platform game for my university project using the canvas element and Javascript. I'm well on my way, but I'm stuck at how to see if a certain key is being pressed in my players update loop.
I was thinking like this:
if(d) {
// move player right
} else if(a) {
// move player left
} else if(w) {
// move player up
} else if(s) {
// move player down
}
That's psudocode, obviously. The only resources to key presses in Javascript that I can find are events, nothing to see if a key is being pressed at a certain point.
Can anyone shed some light on this?
Setup 4 boolean variables if key is up or down. On keydown set it to true, on keyup set it to false. Than you can do if(key_d == true) { // key d is pressed }
That's the best way to do it. Its not "hacky", add event listeners to handle key presses.
I don't think you can get around using keydown, keyup, or keypress for determining which keys are pressed. However, instead of running this code within one of those event handlers, you could set and unset some global flag within them. Then, when this code runs (I'm assuming it'll be on some kind of interval?), it could check for the flag.
You need an event listener.
//function foo, returns keypress
function foo(e){
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
var key=(evt.charCode)?evt.charCode:
((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
return key;
}
//set event listener
//you could also attach this to your canvas, but that will require tricks
//to make the canvas focusable
document.addEventListener('keydown', foo);

Categories

Resources