How to Use Go-SDL2: Tutorial

Solindek
4 min readJul 26, 2024

The Simple DirectMedia Layer (SDL) is a cross-platform library designed to provide low-level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. The Go-SDL2 binding enables Go developers to utilize the SDL library’s capabilities in their Go applications. This tutorial will guide you through the process of setting up and using Go-SDL2 to create a basic application.

Introduction

Go-SDL2 is a powerful tool for game development and multimedia applications in Go. By leveraging SDL2, developers can access a wide range of features to build performant and visually appealing applications. This tutorial aims to provide a step-by-step guide to get you started with Go-SDL2.

Setting Up Your Environment

Before diving into coding, it’s essential to set up your development environment properly.

Installing Go

First, ensure you have Go installed on your machine. You can download the latest version of Go from the official website.

Installing SDL2

Next, install SDL2 on your system. The installation process varies depending on your operating system.

For linux:

$ sudo apt-get install libsdl2-dev

For MacOS:

$ brew install sdl2

For Windows:
Download the development libraries from the SDL2 website and follow the installation instructions.

Creating Your First Go-SDL2 Project

Let’s create a simple Go-SDL2 project that opens a window and handles basic events.

Initializing SDL2

Start by creating a new directory for your project and initializing a Go module:

$ mkdir go-sdl2-demo
$ cd go-sdl2-demo
$ go mod init go-sdl2-demo

Create a new file named main.go and add the following code to initialize SDL2:

package main

import (
"github.com/veandco/go-sdl2/sdl"
"log"
)

func main() {
if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {
log.Fatalf("Failed to initialize SDL: %s", err)
}
defer sdl.Quit()
}

After this code we should create a window by using this code:

window, err := sdl.CreateWindow("Go-SDL2 Demo", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 800, 600, sdl.WINDOW_SHOWN)
if err != nil {
log.Fatalf("Failed to create window: %s", err)
}
defer window.Destroy()

Handling events

To keep the window open and respond to user inputs, we need to handle SDL events:

running := true
for running {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event.(type) {
case *sdl.QuitEvent:
running = false
}
}
}

Rendering Graphics

Finally, let’s add some basic rendering to our window:

renderer, err := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
if err != nil {
log.Fatalf("Failed to create renderer: %s", err)
}
defer renderer.Destroy()

for running {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event.(type) {
case *sdl.QuitEvent:
running = false
}
}

renderer.SetDrawColor(0, 0, 0, 255)
renderer.Clear()

renderer.SetDrawColor(255, 0, 0, 255)
renderer.FillRect(&sdl.Rect{X: 100, Y: 100, W: 200, H: 200})

renderer.Present()
}

This code will render a red rectangle on our window!

Advanced Topics

Once you have the basics down, you can explore more advanced features of Go-SDL2.

Handling Audio

SDL2 supports audio playback, which you can use to add sound effects and music to your application. Here’s a simple example:

if err := sdl.Init(sdl.INIT_AUDIO); err != nil {
log.Fatalf("Failed to initialize SDL audio: %s", err)
}
defer sdl.Quit()

audioSpec := &sdl.AudioSpec{
Freq: 44100,
Format: sdl.AUDIO_S16LSB,
Channels: 2,
Samples: 4096,
}
audioID, err := sdl.LoadWAV("path/to/audio.wav", audioSpec, &audioBuffer, &audioLength)
if err != nil {
log.Fatalf("Failed to load WAV file: %s", err)
}
defer sdl.FreeWAV(audioBuffer)

if err := sdl.OpenAudio(audioSpec, nil); err != nil {
log.Fatalf("Failed to open audio: %s", err)
}
sdl.QueueAudio(1, audioBuffer, audioLength)
sdl.PauseAudio(false)

Working with Textures

Textures are essential for rendering images. Here’s how to load and display a texture:

img.Init(img.INIT_PNG)
defer img.Quit()

texture, err := img.LoadTexture(renderer, "path/to/image.png")
if err != nil {
log.Fatalf("Failed to load texture: %s", err)
}
defer texture.Destroy()

renderer.Copy(texture, nil, &sdl.Rect{X: 100, Y: 100, W: 200, H: 200})
renderer.Present()#### Managing Game Loops

A robust game loop ensures smooth performance. Here’s a basic example:

var deltaTime float64
var lastTime = sdl.GetTicks()

for running {
var currentTime = sdl.GetTicks()
deltaTime = float64(currentTime-lastTime) / 1000.0
lastTime = currentTime

// Handle events
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event.(type) {
case *sdl.QuitEvent:
running = false
}
}

// Update game state
update(deltaTime)

// Render graphics
renderer.SetDrawColor(0, 0, 0, 255)
renderer.Clear()

render(renderer)

renderer.Present()
}

Conclusion

Go-SDL2 is a powerful binding that brings the capabilities of SDL2 to Go developers, enabling the creation of high-performance multimedia applications and games. This tutorial covered the basics of setting up your environment, creating a window, handling events, and rendering graphics. Additionally, we explored advanced topics such as handling audio, working with textures, and managing game loops. With these foundations, you’re well-equipped to start building your Go-SDL2 applications.

Happy coding!

--

--

Solindek
0 Followers

Hobbyist programmer, interested in computers, electronics, robotics and physics ⚡️