Ebiten-纯Golang开发的跨平台游戏引擎

imageimageimageimage

Go语言不是让你玩的啊喂!

昨天跟好基友聊开发的事,他说他等着闲下来的时候就用PYGame写个像那个最近挺火的"文X游X"一样的游戏.(没收广告费啊!)

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

这能忍吗?为了给广大Golang开发者报仇,我决定去问问度娘.

不编故事了,我们直接进入正题...


imageimageimageimage
GitHub地址:https://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作者希望有人能够参与编写和翻译他的文档,我已经向他发邮件询问了.

如果大家希望我做一个正式教程的话,请留言

2022年3月6日 14:11:53 更新 中文翻译已发布:https://ebiten-zh.vercel.app/

posted @ 2021-09-19 17:06  Maicarons  阅读(4532)  评论(6编辑  收藏  举报
商务邮箱:maicarons#outlook.com