veandco / go-sdl2

SDL2 binding for Go
https://godoc.org/github.com/veandco/go-sdl2
BSD 3-Clause "New" or "Revised" License
2.18k stars 219 forks source link

Screen flickering when drawing Text ( as in the example ) #423

Closed Matias-Barrios closed 4 years ago

Matias-Barrios commented 4 years ago

Hi All!,

I am having troubles while applying text to the game I am developing. While the text itself renders correctly, the problem arises as I need to call window.UpdateSurface() which causes flickering. ( Its like there are two screens , the one containing the game and a black screen containing the red text which are constantly trying to overlap themselves ).

This is the exact line in my code where I am calling the method I coded : https://github.com/Matias-Barrios/SDL_Universe/blob/master/main.go#L111

Which calls this method :

func DrawText(text string, font *ttf.Font, window *sdl.Window) {
    var surface *sdl.Surface
    var solid *sdl.Surface
    solid, err := font.RenderUTF8Solid(text, sdl.Color{255, 0, 0, 255})
    if err != nil {
        log.Fatalln("Render Solid - ", err.Error())
    }
    defer solid.Free()

    surface, err = window.GetSurface()
    if err != nil {
        log.Fatalln("Get surface - ", err.Error())
    }

    if err := solid.Blit(nil, surface, nil); err != nil {
        log.Fatalln("blit: ", err.Error())
    }
}

Maybe I'm just following the example give on this repo too linearly.

Can someone point out if my implementation of DrawText is off?

Thanks in advance!

Matias-Barrios commented 4 years ago

Oh my bad! I finally got it. This is my function now :+1:


func DrawText(text string, font *ttf.Font, r *sdl.Renderer) {
    solid, err := font.RenderUTF8Solid(text, sdl.Color{255, 0, 0, 255})
    if err != nil {
        log.Fatalln("Render Solid - ", err.Error())
    }
    defer solid.Free()
    t, err := r.CreateTextureFromSurface(solid)
    if err != nil {
        log.Fatalf("Failed to create texture: %s\n", err)
        os.Exit(5)
    }
    r.Copy(t, nil, &sdl.Rect{0, 0, 100, 100})
}

Sorry for the any inconvenience!