|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "The keyboard package" |
| 4 | +date: 2017-6-10 19:45:11 +0200 |
| 5 | +author: arcadio |
| 6 | +categories: keyboard packages |
| 7 | +heropic: /pictures/keyboard.jpg |
| 8 | +--- |
| 9 | + |
| 10 | +The keyboard is one of the most popular input methods in PC games, and thanks to the `keyboard` package it is really easy to incorporate it into your game. |
| 11 | + |
| 12 | +First of all, you will need to add the package as a dependency to your game. You can do it using the command line `clockwork-tools`, opening a command line in your project folder and typing |
| 13 | + |
| 14 | +`clockwork add keyboard` |
| 15 | + |
| 16 | +Once you have added the dependency, you just need to spawn a `keyboard` object in any level you want to depect keyboard input. Add it to the level like this: |
| 17 | + |
| 18 | +{% highlight xml %} |
| 19 | +<object name="keyboard" type="keyboard" x="0" y="0" ></object> |
| 20 | +{% endhighlight %} |
| 21 | + |
| 22 | +and you will be ready to start detecting keyboard input! |
| 23 | + |
| 24 | +The `keyboard` object you just created will trigger two events, `keyboardDown` and `keyboardUp`, that you can listen to in order to find out when a key is pressed or released. For example, this would be a component that will move right when a certain key is pressed, and move left when another one is released: |
| 25 | + |
| 26 | +{% highlight js %} |
| 27 | + { |
| 28 | + name: "someObject", |
| 29 | + events: [ |
| 30 | + { |
| 31 | + name: "keyboardDown", code: function (event) { |
| 32 | + if(event.key==65){ // 'A' is pressed |
| 33 | + this.var.$x++; |
| 34 | + } |
| 35 | + } |
| 36 | + }, |
| 37 | + { |
| 38 | + name: "keyboardUp", code: function (event) { |
| 39 | + if(event.key==66){ // 'B' is released |
| 40 | + this.var.$x--; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + ] |
| 45 | + } |
| 46 | +{% endhighlight %} |
| 47 | + |
| 48 | +Just like that, you can add your own logic to detect keyboard input and act acordingly. |
| 49 | + |
| 50 | +The key code corresponding to each key is the standard one reported by the browser, [here you can find a list of the most key codes](https://gist.github.com/arcadiogarcia/e477a424eb9a4355724fdfed8ad7469b), or you could just log them (via `this.engine.debug.log(event.key)`) and find out the numbers for the keys you are interested in. |
| 51 | + |
| 52 | +Finally, remember that if you need to remember something about how the component is used, you can quickly access the package documentation from Visual Studio Code, running the `Browse Clockwork package documentation` command. |
0 commit comments