-
Notifications
You must be signed in to change notification settings - Fork 2
Keyboard
#Keyboard
Keyboard input is really straight forward, probably easyer than mouse input. For the most part we just want to check if a key is up or down. We can do so with the following functions:
public bool KeyDown(OpenTK.Input.Key key) {
public bool KeyUp(OpenTK.Input.Key key) {
public bool KeyPressed(OpenTK.Input.Key key) {
public bool KeyReleased(OpenTK.Input.Key key) {
These functions are similar to those in the WinformGames framework, i don't think an in-depth explanation is needed. At any point you can also obtain an array of all the keys currently pressed down with:
public OpenTK.Input.Key[] GetAllKeysDown() {
It's worth noting the data type of all of these functions, it's OpenTK.Input.Key. Again, we're just using the built in OpenTK enumerations
#Sample app We're going to build this application, it just displays a bunch of information about the keyboard. We'll also add a little key controlled square.
####First, let's print all pressed keys
For this you are going to need to create a static list of keys, i just called mine input.
In Update, clear the list, then call the AddRange method of the list to add the entire array returned by GetAllKeysDown to the list.
In the render function, build and draw the appropriate strin, it should look like: "Keyst down: , etc...". Here is a screenshot of what mine looks like
####Next, display the states of a single key For this next part we're going to print out four booleans. One for each state of the space key. Print the following:
- **Space key is down: ** value
- **Space key is up: ** value
- **Space key is pressed: ** value
- **Space key is released: ** value
Each of these coresponds to a function, actually writing the code should be fairly straight forward. If the game is running at 60FPS, the change for pressed and released to true and back to false might be too fast to see. At this point, this is what my app looks like:
####Finally, let's move a square on screen For this last part, make a static RectangleF, i called mine position. I start mine out at X 100, Y 100 with a width and height of 20.
Update the Render function to draw a Red square at the above created rectangle. If you put the function call to draw the rectangle before the calls to render text then the rectangle will render under the text.
Finally, in update moify the position. If up or W is down, subtract from positon y. Do the appropriate actions for down/s, left/a and right/d. How much is the X and Y of position moved each frame? I moved mine by 50 pixels. That's 50 * e.Time, cast to a float. This is what mine looks like
####Finished That's it, keyboatd is a pretty simple input to use. If you are having trouble writing any of the above code, check out my implementation