3

我需要将可编写脚本的 NPC 放入我当前的游戏项目中。项目本身是用 C++ 语言开发的。我将使用 Luabind 来绑定 lua 和 c++。

当某些 NPC 点击或计时器被激活时,我需要调用 NPC 函数。目前我停留在 2 个 NPC 脚本设计之间。

  1. 使用一种 npcname_action 来区分每个 NPC。
    给每个不同的NPC起名字有点麻烦。
    我仍在考虑如何在我的项目中实现这一点。
    例子:

    HotelBellboy12_Click() { .. }  
    HotelBellboy12_TimerAction() { .. }
    
  2. 使用函数名。
    每个 npc 都有自己的 lua 文件。
    我正在考虑将脚本加载到内存中,并在需要时luaState使用luaL_loadbuffer
    示例加载:

    OnClick() { .. }
    OnTimerAction() { .. }
    

哪个更好,为什么?

4

2 回答 2

3

你可以使用另一种设计。

利用表键和值可以是任何类型的事实。

假设 npc 是一个包含所有 NPC 的表。它的键是 NPC 的名字,它的值是另一个表。这个其他的表键是动作,它的值是这个动作的函数。所以,如果你想让 bob 在点击时跳起来,而 alice 在计时器后哭泣,只需执行以下操作:

npc.bob.click = function () jump() end
npc.alice.timer = function () cry() end
于 2011-01-27T16:21:41.720 回答
1

我以前做过类似的事情,我使用了类似于你的#2 选项的东西。当地图加载时,我会加载一个包含所有 NPC 数据的配置 Lua 文件;其中是用于 NPC 的脚本文件的名称。

When I need to load the NPC in the game I compile the Lua file. NPC's can use a 'model' NPC type to dictate most of the common behavior (for example a Merchant type or a Commoner type) which is specified in the NPC configuration. These model types provide all the basic functionality such as providing a trade window when clicked. The specific NPC's use functions like OnClick() to override their model and provide custom handlers.

This worked pretty well for me, although it ends up being a large volume of scripts if your game gets large.

于 2011-01-27T16:39:30.380 回答