Converting Keyboard Events into Avatar Movement
By playing with the keyboard event listener, we now know the numbers that correspond to each of the four arrow keys. We convert those arrow keys and numbers into avatar movement like this:
Arrow Key | Computer Number | Avatar Direction |
---|---|---|
Left | 37 | Left |
Up | 38 | Forward |
Right | 39 | Right |
Down | 40 | Back |
So let’s make this happen. Remove the alert(event.keyCode) line inside the document.addEventListener. Replace it with the following code, starting with the var code statement.
| document.addEventListener('keydown', function(event) { |
| var code = event.keyCode; |
| if (code == 37) avatar.position.x = avatar.position.x-5; // left |
| if (code == 38) avatar.position.z = avatar.position.z-5; // up |
| if (code == 39) avatar.position.x ... |
Get 3D Game Programming for Kids now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.