KeyPressed doesn’t work

I’m pretty new to coding, and I have been trying to follow some of The Coding Train’s videos. But every video that he uses the keyPressed function, or anything that involves the keyboard in gameplay, nothing happens for me, like nothing moves when they are supposed to. I’m using a chrome book if that helps. If anybody can help me, that would be great.

Hey and welcome to the forum!

Do you use processing or p5?

Can you post your entire code please?

Please remember that everything is case sensitive in processing, so it’s setup and draw etc.

Regards, Chrisir

I’m using p5, and I know it sounds stupid, but how do I open a file?

Actually, I figured out how to open a file.
I’m trying to code snake, it is not done, but in The Coding Train’s video, his is moving when he hits the arrow keys and mine isn’t. I’m pretty sure the code is the same though.
Here it is:

this one is for my sketch.js file:
var s;

function setup() {
createCanvas(600, 600);
s = new Snake();

}

function draw() {
background(51);
s.update();
s.show();
}

function keyPressed() {
if (keyCode === UP_ARROW) {
s.dir(0, -1);
} else if(keyCode == DOWN_ARROW) {
s.dir(0, 1);
} else if(keyCode == RIGHT_ARROW) {
s.dir(1, 0);
} else if(keyCode == LEFT_ARROW) {
s.dir(-1, 0);
}
}

This one is for my snake.js file:
function Snake() {
this.x = 0;
this.y = 0;
this.xspeed = 1;
this.yspeed = 0;

this.dir = function(x, y) {
this.xspeed = x;
this.yspeed = y;
}

this.update = function() {
this.x = this.x + this.xspeed;
this.y = this.y + this.yspeed;
}

this.show = function() {
fill(255);
rect(this.x, this.y, 10, 10);

}
}

does anybody have any idea on why that’s not working?

please format your code posting by pasting it into the

</> code button

of the editor header menu ( context name: Preformatted text )
it looks like
```
type or paste code here
```

also can use the ``` manually above and below your code.

thank you.


but actually, much more easy to play / help is you
give us the link to your
https://editor.p5js.org
project


if you make the snake function in a extra
snake.js
file, did you declare it in index.html?

https://editor.p5js.org/Bronx_Bombers/sketches/tx74QyQyY
yes, i put it in the index.html

1 Like

It works here!
After I click on the canvas with the mouse I can use the keyboard.

:slight_smile:

1 Like

OMG! i feel like such an idiot! sorry to waste your time. It works

The program/ canvas didn’t have the focus initially, so we had to click the mouse

Some discussions on this topic:
[Automatically make sketch active after pressing play · Issue #654 · processing/p5.js-web-editor · GitHub]
[Must click into canvas preview pane before key events are recognized · Issue #993 · processing/p5.js-web-editor · GitHub]

I also found this example:

:slight_smile: