Hello, and welcome back to my small tutorial how to begin your adventure with WebAssembly using Go.
This is 2 part of 5. You can find other parts here:
- WebAssembly 2D game with Go. Part 1: Boilerplate.
- WebAssembly 2D game with Go. Part 3: Drawing character.
- WebAssembly 2D game with Go. Part 4: Moving character.
- WebAssembly 2D game with Go. Part 5: Docker stuff & Deploy
Now, let's try to actually render something with Ebiten.
First of all, let's define our Game struct to keep game state in it. We will add an integer count property, just for educational purposes - it will be removed in future.
Also, Ebiten requires our game to have several methods to work with:
- Layout - for defining our available "game space" (screen size)
- Update - for updating our game state and keep all game logic
- Draw - to render game based on our game state.
Let's start with Layout.
According to documentation, layout accepts a native outside size and returns the game's logical screen size.
Next, let's write a mock update function, just to see all things working correctly.
As you can see, it just updates our count property on every call. In Draw method we will output its value to console, just to demonstrate how Update and Draw method's working together.
Back in days, you didn't needed actually two methods to make things work - It was enough to do all stuff in Update method. But as the result, your code become messy and basically unreadable. It is always a nice way to separate application logic from render.
Now, to Draw method.
Here, we are telling our program that for every frame that game draws, it must fill our screen with #f0f0f0 RGB color and log into console our count property from game state.
Finally, let's start our game in main func, and review our main.go file.
Cool! Now we can re-build our main.go to wasm same way as we built it before, and see result in browser!
GOOS=js GOARCH=wasm go build -o public/game.wasm src/main.go
Besides a canvas filled with #f0f0f0 color, if you open a console you will see a count property logged in console.
And we arrived to our second git tag. You can checkout same way as last time to see all necessary code.
git checkout first_steps