Ebiten
ebiten是一个简单的使用纯go实现的游戏,使用这个库即可以实现go语言代码的学习,又可以实现对游戏编程的了解。
Hello world
让我们以一个Hello world!开始ebiten的学习,
完整代码实现如下:
package main
import (
"github.com/hajimehoshi/ebiten"
"github.com/hajimehoshi/ebiten/ebitenutil"
"log"
)
type Game struct {
}
func (g *Game) Update() error {
return nil
}
func (g *Game) Draw(screen *ebiten.Image) {
ebitenutil.DebugPrint(screen, "Hello world!")
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return 320, 240
}
func main() {
ebiten.SetWindowSize(720, 480)
ebiten.SetWindowTitle("Hello world!")
if err := ebiten.RunGame(&Game{}); err != nil {
log.Fatal(err)
}
}
运行效果如下:

- 导入所需模块
其中import的两个比较重要的库,一个是"github.com/hajimehoshi/ebiten"这里面实现的事ebiten的核心代码,"github.com/hajimehoshi/ebiten/ebitenutil"里面实现的是ebiten常用的一些工具库。
- 定义数据结构体
type Game struct {
}
Game结构体,该结构体实现了ebiten.Game接口。该接口实现了第三步中的三个接口函数:
- 实现
ebiten.Game接口
// 图像刷新函数
// 这个接口会按照每秒60(默认)次的频率进行调用
// 这个函数正常运行会一直返回nil的error,当返回非nil值时,你的game将会被挂起
func (g *Game) Update() error {
return nil
}
//绘图函数
// 没帧图 都会调用Draw函数进行绘制,如果你想要60帧,那你就得每秒调用该函数60次
func (g *Game) Draw(screen *ebiten.Image) {
ebitenutil.DebugPrint(screen, "Hello world!")
}
// 该接口接受外部尺寸,即桌面尺寸,返回游戏尺寸,即无论桌面尺寸多大,游戏的尺寸是固定的(返回的事固定值)
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return 320, 240
}
- 主函数调用
ebiten.SetWindowSize(720, 480)设置窗口大小,要是不设置就使用默认窗口大小。
ebiten.SetWindowTitle("Hello world!")设置窗口标题
ebiten.RunGame(&Game{})游戏主循环
995



被折叠的 条评论
为什么被折叠?



