Reputation: 21
I have a sprite that animates on the x-axis via the left and right arrow keys. It is setup to move on 'keydown' and stop on 'keyup'. The problem is, it only animates after the second key press. I've also tried holding down either left or right keys - which upon 'keyup the sprite still animates. Again, this cancels out after the second press of the 'same' key.
My events start at line 54.
I've set up a console log, so it may be easier to get an understanding by opening up the console while taking a look at the events.
Oh yeah, I'm using the EaselJS library, and the Mousetrap keyboard shortcut library; not sure that makes a difference because my problem is essentially linked to the browser. Any work-around or help on my existing code would be awesome.
function move() {
if (rightHeld) { // move right
var speed = 3;
chuck.x += speed;
chuck.scaleX = 1;
} // end move right
if (rightHeld && keyDown == false) { // animate move right
chuck.gotoAndStop('idle');
chuck.gotoAndPlay('walk');
keyDown = true;
} // end animate move right
if (leftHeld) { // move left
var speed = 3;
chuck.x -= speed;
chuck.scaleX =- 1;
} // end move left
if (leftHeld && keyDown == false) { // animate move left
chuck.gotoAndStop('idle');
chuck.gotoAndPlay('walk');
keyDown = true;
} // end animate move left
} // end function move
/* KEYDOWN*/
function handleKeyDown(event) {
Mousetrap.bind('right', function () {
rightHeld = true;
console.log('keydown right');
}, 'keydown'); // end 'right'
Mousetrap.bind('left', function () {
leftHeld = true;
console.log('keydown left');
}, 'keydown'); // end 'left'
} // end function handleKeyDown
/* KEY UP */
function handleKeyUp() {
Mousetrap.bind('right', function () {
chuck.gotoAndStop('walk');
chuck.gotoAndPlay('idle');
rightHeld = false;
keyDown = false;
console.log('keyup right');
}, 'keyup'); // end 'right'
Mousetrap.bind('left', function () {
chuck.gotoAndStop('walk');
chuck.gotoAndPlay('idle');
leftHeld = false;
keyDown = false;
console.log('keyup left');
}, 'keyup'); // end 'left'
} // end function handleKeyUp
Thanks smart people!
Upvotes: 0
Views: 2227
Reputation: 7336
You are binding the event listener on the first keydown
/keyup
, thats why it doesn't work on the first try. Check the fixed fiddle.
Change:
window.onkeydown = handleKeyDown;
window.onkeyup = handleKeyUp;
to:
handleKeyDown();
handleKeyUp();
In other words, you are doing something like this:
button.onclick = function () {
button.onclick = function () {
alert("you click!");
};
};
(see this fiddle as an example for the code above)
The first click will bind the alert
for the next click, but it doesn't do anything else. Thats why it works from the second time, and something similar was happening with your code.
Upvotes: 3