Ebiten-純Golang開發的跨平台遊戲引擎

imageimageimageimage

Go語言不是讓你玩的啊喂!

昨天跟好基友聊開發的事,他說他等着閑下來的時候就用PYGame寫個像那個最近挺火的”文X游X”一樣的遊戲.(沒收廣告費啊!)

基友突然嘲笑我:”你家Go是不是只能玩黑底白字啊?”

這能忍嗎?為了給廣大Golang開發者報仇,我決定去問問度娘.

不編故事了,我們直接進入正題…


imageimageimageimage
GitHub地址://github.com/hajimehoshi/ebiten

開發者大大 星一(はじめほしHajime Hoshi)對Ebiten的介紹:

Ebiten is an open source game library for the Go programming language. Ebiten’s simple API allows you to quickly and easily develop 2D games that can be deployed across multiple platforms.
Ebiten是個用Go寫的開源的遊戲引擎.俺的炒雞簡單API可以讓你快速碼出炒雞🐮的2D遊戲,還可以整到各個平台上!

搜嘎,還是很謙虛嘛.

開始開發!

第一步 安裝

Go 最低支持版本:1.13+
然後直接:

go get github.com/hajimehoshi/ebiten/v2
go run -tags=example github.com/hajimehoshi/ebiten/v2/examples/rotate

如果看到這個鬼畜圖片說明安裝正常:
image

Windows不需要CGO,其他平台需要.

各平台詳細安裝步驟請康開發者的 奇怪指南

第二步 哈嘍,沃德

package main

import (
	"log"

	"github.com/hajimehoshi/ebiten/v2"            //ebiten本體
	"github.com/hajimehoshi/ebiten/v2/ebitenutil" //ebiten工具集
)

type Game struct{}//Game結構體

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(640, 480)//窗口大小
	ebiten.SetWindowTitle("Hello, World!")//窗口標題
	if err := ebiten.RunGame(&Game{}); err != nil {
		log.Fatal(err)
	}
}

然後就會在屏幕右上角輸出一個”Hello, World!”
image

沒有10年遊戲開發經歷的你可能會有疑問了:這玩意叫遊戲引擎?我用腳摳的也比他好.

我們不妨再加幾行:

type Game struct{
	i uint8
}
func Hex2RGB(color16 string ,alpha uint8) color.RGBA  {
	r, _ := strconv.ParseInt(color16[:2], 16, 10)
	g, _ := strconv.ParseInt(color16[2:4], 16, 18)
	b, _ := strconv.ParseInt(color16[4:], 16, 10)
	return color.RGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: alpha}
}

func (g *Game) Draw(screen *ebiten.Image) {
	g.i++
	if  g.i < 255 {
		screen.Fill(Hex2RGB("#0dceda", g.i))
		else{g.i=0}
		ebitenutil.DebugPrint(screen, fmt.Sprintf("Hello,ebiten!\nTPS: %0.2f\nFPS: %0.2f", ebiten.CurrentTPS(),ebiten.CurrentFPS()))
}

效果如何呢?有沒有驚艷到你呢?

解釋幾個名詞:

FPS:遊戲佬都知道,幀數幀數,玩家一生的痛!

TPS(ticks per second):每秒滴答數,說白的就是每秒執行函數的次數,鎖定60.

作者推薦在Debug時看TPS,因為在某些情況下,FPS是不可靠的.

最後 Build,並扔給好基友

ebiten在build時毫無問題,非常絲滑,我也在裝載win7的古董電腦上跑了一下,完全兼容.

至於做跨平台嘛…就需要研究一下啦!


imageimageimageimage

這次的教程滿意嗎?

喜歡的話就分享給各路大神吧!

對了,ebiten作者希望有人能夠參與編寫和翻譯他的文檔,我已經向他發郵件詢問了.

如果大家希望我做一個正式教程的話,請留言