Hello, and welcome back to my small tutorial how to begin your adventure with WebAssembly using Go.
This is 4 part of 5. You can find other parts here:
- WebAssembly 2D game with Go. Part 1: Boilerplate.
- WebAssembly 2D game with Go. Part 2: First Steps.
- WebAssembly 2D game with Go. Part 3: Drawing character.
- WebAssembly 2D game with Go. Part 5: Docker stuff & Deploy
Alright, time to do some interesting stuff! Let's try to move our character.
For accomplishing that, we need to do 3 things in our Update func:
- Listen for key press
- Change character coordinates
- Change character stance
But before that, we need to add to our Game struct positionX and positionY coordinates, and create a speed constant to control our character speed:
Now, let's start with key press listening. We will use inpututil from Ebiten for that:
Yeah, code is pretty ugly here, i know we can do it, like, more declarative way, but for now - we are concentrating on making things to work.
After that, we can write our first handle for key press:
Basically, what we doing here is:
- Adding speed value to our main axis position (posY for Up/Down, posX for Left/Right)
- Checking if we already have correct stance row and column, and if we have, just set correct column to make "move animation"
- Choosing proper row for stances
- Blocking character to go off the screen. For that, we checking if character main axis position lower then 0, then setting it equal to 0, or greater then screenHeight (for Down) or screenWidth (for Right) setting it equal to screenHeight/screenWidth
2nd point in the list sounds a bit complex, isn't it? Let me try to visualize what we trying to do:
See? We moving our virtual 65x65 frame over stances, to make animation.
Now, repeat it for every key we listen, and here is our Update func:
Alright! Time to render all that stuff in Draw func, and we are ready to control our character!
To render our character image at coordinates we need, we used a DrawImageOptions type. With method Translate, we can modify coordinates of our image on screen.
Piece of cake, isn't it? Now, all is left is run
make dev to rebuild all the stuff, and we can see the result in browser:
As usual, you can use git tag to checkout all the code at this point.
git checkout advanced_movement
Basically, that's all for coding, now to DevOPS section, where we will find out how to bundle all things together with parcel.