Beginner's Guide: Make things move with keyboard input in P5js
Vložit
- čas přidán 5. 08. 2024
- Code from video: editor.p5js.org/BarneyCodes/s...
If you want to make a game in P5js, you're probably going to want to be able to move the player around the screen using the keyboard. Even if you're just wanting to add a bit of interactivity to your P5js project, the keyboard is a great way to do it!
In this video I'll show you the best method - that even a beginner can understand - for reading the keys that have been pressed on the keyboard and how to use that information to update your player (or other object) to get them moving around the screen!
Follow me:
Support the channel: www.youtube.com/@BarneyCodes/...
Twitter: / barneycodes
Reddit: / barneycodes
Chapters:
0:00 Intro
0:15 The Player class
1:10 Movement vector
1:44 How NOT to do keyboard input
2:55 Correct keyboard input
3:52 Final result
#creativecoding #p5js #javascript
What sort of game are you making in P5js?
1:26 nice solution for this, didn't know about the setMag function that's cool.
Thanks, it's pretty handy! There's quite a few really helpful vector functions, definitely worth checking them out!
how can I make this keep going instead of holding on to arrow keys
Great question! You should be able to do this fairly simply by doing everything inside the same function (either keyPressed or keyReleased, it'll depend on how you want it to work!), then all you need to do is check if the key is already in the pressedKeys object like this:
if(pressedKeys[key]) {
delete pressedKeys[key];
} else {
pressedKeys[key] = true;
}
This way the key toggles every time you pressed it! Hope that helps!