《Lua游戏AI开发指南》一2.3 扩展SandboxApplication类

    xiaoxiao2024-03-10  119

    本节书摘来异步社区《Lua游戏AI开发指南》一书中的第2章,第2.3节,作者: 【美】David Young(杨) 译者: 王磊 责编: 陈冀康,更多章节内容可以访问云栖社区“异步社区”公众号查看。

    2.3 扩展SandboxApplication类

    项目创建好之后,你需要为Premake创建3个空白文件。创建如下的源文件和头文件:

    src/my_sandbox/include/MySandbox.h src/my_sandbox/src/MySandbox.cpp src/my_sandbox/src/main.cpp

    现在就可以运行vs2008.bat、vs2010.bat、vs2012.bat或者vs2013.bat来重新生成Visual Studio解决方案了。然后,当打开这个解决方案时,你就能看到新的my_sandbox项目了。

    每个沙箱示例程序都需要扩展SandboxApplication基础类来声明可执行的Lua脚本的位置。

    遵照下面的模式来声明你的MySandbox类:

    MySandbox.h: #include "demo_framework/include/SandboxApplication.h" class MySandbox : public SandboxApplication { public: MySandbox(void); virtual ~MySandbox(void); virtual void Initialize(); };

    继承SandboxApplication类可以提供一些基础的功能。目前我们只需要重载Initialize函数来添加Lua脚本资源的路径。

    继承SandboxApplication还能重载Update和Cleanup等函数。任何其他的C++代码都可以通过这些函数注入到主应用程序中。

    当重载这些函数时,你总是应该调用Sandbox Application基类的原始实现,因为它们处理了沙箱的清理、初始化和更新等功能。在沙箱的源文件中,只需要设置沙箱的Lua脚本资源的路径,并调用父类的Initialization函数。

    MySandbox.cpp: #include "my_sandbox/include/MySandbox.h" MySandbox:: MySandbox () : SandboxApplication("My Sandbox") {} MySandbox::~ MySandbox () {} void MySandbox::Initialize() SandboxApplication::Initialize(); //Relative location from the bin/x32/release/ or //bin/x32/debug folders AddResourceLocation("../../../src/my_sandbox/script"); }

    最后,你可以在main.cpp文件中添加一点启动代码来开始你的应用程序:

    main.cpp: #include "my_sandbox/include/MySandbox.h" #include "ogre3d/include/OgreException.h" #define WIN32_LEAN_AND_MEAN #include "windows.h" int main() { MySandbox application; try { application.Run(); } catch(Ogre::Exception& error) { MessageBox( NULL, error.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); } } 相关资源:lua游戏ai开发指南 源码
    最新回复(0)