Go SDL2 游戏开发入门12-旋转 翻转
前言
sdl2 提供了快速旋转和翻转的功能, 这一节我们就来看看如何使用
代码
代码这边我把 texture 结构体单独拎出来放到一个文件里, 代码量多了之后就要注意工程管理了
package main import ( "github.com/veandco/go-sdl2/img" "github.com/veandco/go-sdl2/sdl" ) type Texture struct { t *sdl.Texture W int32 H int32 } func (this *Texture) LoadFromFile(path string) bool { img, err := img.Load(path) if err != nil { panic(err) } this.t, err = Grender.CreateTextureFromSurface(img) if err != nil { panic(err) } this.W = img.W this.H = img.H img.Free() return true } func (this *Texture) Render(src, dst *sdl.Rect, angle float64, center *sdl.Point, flip sdl.RendererFlip) { Grender.CopyEx(this.t, src, dst, angle, center, flip) } func (this *Texture) setColor(r, g, b uint8) { this.t.SetColorMod(r, g, b) } func (this *Texture) SetAlpha(a uint8) { this.t.SetAlphaMod(a) } func (this *Texture) SetBlendMode(blend sdl.BlendMode) { this.t.SetBlendMode(blend) } func (this *Texture) Free() { this.t.Destroy() } func (this *Texture) GetW() int32 { return this.W } func (this *Texture) GetH() int32 { return this.H }
- 注意这里有一个新的函数 CopyEx, 它比 Copy 函数多了几个参数, 就是用来控制图片旋转角度这些的
package main import ( "github.com/veandco/go-sdl2/sdl" ) const ( W = 670 H = 520 ) var ( Gwindow *sdl.Window Grender *sdl.Renderer texture *Texture ) func init() { sdl.Init(sdl.INIT_EVERYTHING) Gwindow, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, W, H, sdl.WINDOW_SHOWN) if err != nil { panic(err) } Grender, err = sdl.CreateRenderer(Gwindow, -1, sdl.RENDERER_ACCELERATED) if err != nil { panic(err) } texture = &Texture{} texture.LoadFromFile("../asserts/image/arrow.png") } func main() { flipType := sdl.FLIP_NONE degree := float64(0) running := true for running { for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch t := event.(type) { case *sdl.QuitEvent: println("Quit") running = false break case *sdl.KeyboardEvent: if t.State == sdl.PRESSED { switch t.Keysym.Sym { case sdl.K_a: degree -= 60 case sdl.K_d: degree += 60 case sdl.K_q: flipType = sdl.FLIP_HORIZONTAL case sdl.K_w: flipType = sdl.FLIP_NONE case sdl.K_e: flipType = sdl.FLIP_VERTICAL } } } } Grender.SetDrawColor(128, 128, 128, 255) Grender.Clear() dst := &sdl.Rect{(W - texture.GetW()) / 2, (H - texture.GetH()) / 2, 100, 100} texture.Render(nil, dst, degree, nil, flipType) Grender.Present() sdl.Delay(16) } free() } func free() { texture.Free() Grender.Destroy() Gwindow.Destroy() sdl.Quit() }
- 这段代码的功能就是根据用户输入的不同按键, 将图片旋转不同的角度
- 主循环中读取按键输入, 根据不同的按键设置 degree 角度, flipType 翻转类型
- 最后调用 Render 进行渲染