Help with the function KeyIsDown


#1

How do you use the “KeyIsDown”, because I try and it isn’t working out that well. My code is here:

//Variables
//X and Y Sipmlifying
var y = this.y;
var x = this.x;

function update() {

//Should Make player move. . . 
function keyIsDown(w) {
    y += 10;
}

}

And my object still won’t move. Does anyone know this better than I?
if so thank you so much!


Add examples for keyboard input?
#2

keyIsDown just returns true or false if the specified key is pressed. Just need to add the keyDown function that is called whenever any key is pressed:

function keyDown(){
    if (keyIsDown('W')){
    this.y += 10;
    }
}

I don’t know how better fits your code but I have tested this above and it works fine.
Also notice the ‘W’ with quotes.
Hope it helps! :slight_smile:


#3

Ahh keyIsDown() is actually a pretty special function.

keyIsDown('key') will return true when a certain key is held down, not just when it’s pressed!

So, let’s say you want a function, or action to play every frame the ‘a’ key is held down. You would do this…

function update() {
    if keyIsDown('a') {
        doSomething(); // do something every frame the 'a' key is down
    }
}

doSomething() will run every frame the ‘a’ key is held down!

Now, if you’d like to make this function run once you can use the keyPressed() function like so.

function keyPressed(key) {
    if (key === 'a') {
        doSomething(); // do something once per keypress of the 'a' key. 
    }
}

Let me know if this helps!


#4

Thank you guys so much!