Lua在游戲開發(fā)中應(yīng)用教程
Lua在游戲開發(fā)中應(yīng)用是本文要介紹的內(nèi)容,主要是來了解并學(xué)習(xí)lua中游戲的開發(fā),具體內(nèi)容的實現(xiàn),來看本文詳解。
前些日子一直忙于開發(fā)BigTank項目(下載地址參見劣質(zhì)設(shè)計網(wǎng)站:http://www.buaa-mstc.com,不支持IE),總結(jié)了一些Lua在C#項目中的應(yīng)用方法。
Lua 是一個小巧的腳本語言。作者是巴西人。該語言的設(shè)計目的是為了嵌入應(yīng)用程序中,從而為應(yīng)用程序提供靈活的擴展和定制功能。它的主頁是 www.lua.org。
Lua腳本可以很容易的被C/C++代碼調(diào)用,也可以反過來調(diào)用C/C++的函數(shù),這使得Lua在應(yīng)用程序中可以被廣泛應(yīng)用。不僅僅作為擴展腳本,也可以作為普通的配置文件,代替XML,Ini等文件格式,并且更容易理解和維護。
在C#中使用Lua也十分簡單。
- LuaInterface is a library for integration between the Lua language and Microsoft
- .NET platform’s Common Language Runtime (CLR). Lua scripts can use it to instantiate CLR objects,
- access properties, call methods, and even handle events with Lua functions.
從LuaInterface網(wǎng)站上可以下載到這個庫。在你的項目中引用LuaInterface.dll后就可以開始了。
BigTank項目還沒有確定是否要開源,所以我拿自己寫的電子寵物程序演示一下(它也用了Lua,你可以在實驗室頁面找到它的全部源代碼)。
- C#:
- //...
- /// <summary>
- /// Lua虛擬機
- /// </summary>
- private static Lua luaVM = null;
- /// <summary>
- /// 寵物的構(gòu)造函數(shù)
- /// </summary>
- public Pet(PetForm _petForm, string _petName, string _petPath)
- {
- petState = new PetState();
- petForm = _petForm;
- petName = _petName;
- //構(gòu)造Lua虛擬機以解析寵物AI
- luaVM = new Lua();
- //注冊提供給寵物AI的API函數(shù)
- Type tThis = this.GetType();
- luaVM.RegisterFunction("PetDo", this, tThis.GetMethod("LuaPetDo"));
- luaVM.RegisterFunction("PetDoFrame", this, tThis.GetMethod("LuaPetDoFrame"));
- luaVM.RegisterFunction("Sleep", this, tThis.GetMethod("LuaSleep"));
- //載入AI文件
- luaVM.DoFile(System.AppDomain.CurrentDomain.BaseDirectory + _petPath + "\\ai.lua");
- }
其中RegisterFunction作用是注冊C#代碼中的一個public(***版本的LuaInterface支持private)函數(shù)來供Lua腳本使用,其中無需關(guān)心參數(shù)的個數(shù)以及類型。
- Lua:
- PetDo("Sleep");
執(zhí)行DoFile后會調(diào)用Lua腳本,后者則調(diào)用C#中的PetDo函數(shù)完成指定動作。
小結(jié):Lua在游戲開發(fā)中應(yīng)用教程的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)能對你有所幫助!