This article will explore how to code a character sprite that can walk around on an image background using Golang, the Image package, and the Fyne GUI toolkit
Some time ago, I followed some exciting tutorials by Frank’s Laboratory on how to code games in JavaScript. I have decided to code one of his simple games in Golang using the Fyne GUI toolkit for this article instead of JavaScript.
The structure of the code I present to you here will also be somewhat different from the original by Frank’s Laboratory, given that Golang works differently from JavaScript.
As in his video tutorial, we won’t be building a complete game. You’ll be able to move a character around on a background image using the arrow keys on your keyboard. Nevertheless, this could be the start of an actual game.
The Game Assets
Below, you can see the two-game elements used in this project.
We’ll use a Starwars background and a sprite sheet featuring Chewbacca. “Chewie.” The original links to these assets can be found on the YouTube page of the tutorial by Frank’s Laboratory.
Once you have downloaded them, these PNG image game assets should be placed in a folder called ./assets
below the folder in which the Go code is run.
The Golang Packages That We’ll Be Using
- Fyne: You can find the home page for the Fyne GUI Toolkit here. If you want to know more about Fyne, then my previous articles, which you can find here and here, may also be of interest.
- Image: The documentation for the base Image package from the standard library can be found here.
- Time: This is a standard Golang library. You can find documentation for the Time package here.
An Overview Of The Golang Code
The Player and Game models
In lines 1–16, we define the Player
struct.
The x
and y
fields refer to the position of the player in the game.
The width
and height
are the size of each sprite on the sprite sheet.
The variables frameX
and frameY
refer to the sprite position on the sprite sheet in the x and y directions, respectively.
The field cyclesX
counts the number of sprites in the X direction on the sprite sheet. When the player walks, these sprites will repeatedly be cycled from beginning to end.
The variables upY
, downY
, leftY
, rightY
refer to the specific rows of sprites that correspond to the orientation of the player character.
The variable speed
is the amount added to the player’s x or y position.
There is no ads to display, Please add some