I'm sure that you've heard about arrow keys. They play a big role when creating games.
- How The Arrow Keys Look Like
- Key Code Chart
- How To Use Arrow Keys
- Summary And Game Example
How The Arrow Keys Look Like
Right Arrow Key: ➡️
Left Arrow Key: ⬅️
Up Arrow Key: ⬆️
Down Arrow Key: ⬇️
document.addEventListener is important because it detects if a key is pressed (in our case). The format looks like:
For example, you might have:
This would remove the HTML element that has the
look on hover of the HTML element that has the
Click this to learn more about event listeners, mainly
def your_function(): in Python, you create a shortcut for the code you want to use. Functions are helpful if your using
onmouseover if your in HTML. An example looks like:
Click this to learn more about functions.
if, else if, else
Ah yes, some of the most well known loops. I'm sure that you already know these. These are important, though. We will use them to detect which key is being pressed. Here is an example of an
if, else if, else statement:
Click me to learn more about if else if, else statements.
&& means and.
|| means or. These are useful because if you want to have two keys combined, you can use
&&. If you want to have 2 keys that have the same result, use
|| to save time and make things easier. For example, if I did:
I would get "TRUE". I could use
Click this to learn more about operators.
For those that are only beginners, don't panic.
keydown is a bit more advanced.
keydown is an event, so when a certain key or element is pressed, an event will happen.
keydown is actually an event and it could be used in
Click me to learn more about the jQuery event,
Key Code Chart
|Number 0 key||48|
|Number 1 key||49|
|Number 2 key||50|
|Number 3 key||51|
|Number 4 key||52|
|Number 5 key||53|
|Number 6 key||54|
|Number 7 key||55|
|Number 8 key||56|
|Number 9 key||57|
WASD and Arrow Keys:
|Up Arrow key||38|
|Down Arrow key||40|
|Left Arrow key||37|
|Right Arrow key||39|
You can see the entire keycode chart here. Make sure to not get confused with keydown and keypress because they have different key codes.
How To Use Arrow Keys
Here is an example on how to use the up arrow key:
I don't think that you might understand this. Let me break this down. Our
addEventListener is waiting for a key. The
keydown part detects if a key is pressed. The
function is here to help detect which key is pressed. The
if statement selects which key is pressed. The
|| allows you to have different keys that do the same things.
This is the basic format:
Summary And Game Example
I hope that this tutorial helped you. We have our event waiting for a key to happen. If you still don't understand what's going on, reread what I wrote. I tried to make this informative and easy to understand.
Check out my code if you don't uderstand this. The post is here. My game is just moving blocks. Enjoy!