In this tutorial, we'll be extending our code from Part 1 to listen for user input via keyboards
We have a lot of keys to keep track of when detecting input from keyboards. Rather than storing a bunch of booleans for every key, we can instead use a Set. If the key is contained in the set, then we know the user is currently pressing it, otherwise they're not. We can update the set based off of the keydown
and keyup
events. Here's what our updated InputHandler.js
looks like after doing so
Now let's make it so that the spaceship can move forward, backwards, left, and right using WASD controls. We can do this by updating the update(timeDelta)
function in Spaceship.js
with calls to our new isKeyPressed(code)
function. Here's what that can look like
Running our website now gives us a spaceship we can control in 4 directions, awesome!
Depending on which web browser you used for the last portion, you may or may not have noticed a tiny little bug. For chromium based browsers, hitting ESC to unlock the pointer also clears all keyboard information. This means if you're holding W to move forward, hit ESC, and then release W, the browser won't trigger a keyup
event so by hitting the start button afterwards you'll keep moving forward even though you're not pressing anything
This is a little annoying, and the only solution I can come up with that doesn't make me hate myself is just clearing all keys in our Set _keysPressed
. This does mean that if you keep holding W while you press ESC and then hit the start button you'll no longer be moving, but it's better for the user to have to repress the key to start moving than for them to repress and release the key to stop moving
There's no reason for all Desktop / Laptop users suffer for the sins of Chrome, so let's open up setup.js
and store whether we're using a Chromium based browser using
Great, now we can just add a little check to see if we're using a chromium based browser with our other event listeners in InputHandler.js
, and if so add a pointerlockchange
event listener that will clear _keysPressed
depending on global.sessionActive
Don't forget to import global!
Dope, now everything works in a much more reasonable manner for Chrome users
Hope you enjoyed this tutorial and are excited for the next one because this time I saved the best for last, VR Controller Input!
Feeling generous/want to support me in writing tutorials? Then buy me a coffee, which I'll probably use for boba or almonds (raw and unsalted you heathens) because I don't like coffee
Comment
Please Wait...
Log in/Sign up to comment
Server error, please try again later
...