MAC's Simple NPCs MAC's NPCs v1.3 + Documentation (ENG) Basic Setup 1. To install this addon to your server just unzip all folders to your garrysmod/addons folder and restart the server. Note: This addon will contain two folders mc_simple_npcs and mcd_ui which both must be placed inside your addon folder. If you already have mcd_ui addon, you can skip or update the files, as it was downloaded with my other products. 2. To start setting up an NPC enter the server. Open the game console and type the mcs_setup command to open the setup menu. Note: In order to open you must have superadmin privilege on your server In the setting tab, you can do all configurations. To do it manually edit sh_config.lua file located in mc_simple_npcs/lua/mcs_npcs This menu features autosave on close and autoloads last edited NPC NPC setup NPC Name NPC’s Name will be displayed above it and inside the dialogue box. Example: Unique ID In this text box, you must enter the unique name for the NPC. It used only by the server and it must be unique for each NPC you create. It will also be used as a name for the save file. NPC Name position In this text box, you can adjust the height of the NPC’s name displayed above his head. This can be useful if you use bigger or smaller models. Read more about it in the advanced setup Use limitation By checking this option only one player will be able to use the NPC. This is option is needed if you want to use animation playback in the dialog. See more at The Dialogue setup Dialogue theme Here you can change the dialogue UI themes from the list of supported themes. This will affect only the NPC you are editing. Note: Currently supported themes - Default, Retro, Backbone, Hollow Knight. Model and animation setup To set a model for your NPC, copy and paste the path to the model inside the text box. You can use the Copy from looking entity button to copy the model path from the entity you looking at. You can adjust the NPC model size by dragging the Scale slider. 100% scale will use original model size, 200% doubles it in size, 50% makes it half the original model size. You can preview the model on the side panel, rotate it, and zoom by double-clicking it. If your model supports body groups or skins you will see these panels for adjustment. To make your NPC animated, enter the animation name inside the “NPC animation” text box. By pressing the Get animations button you’ll see a list of all animations for the model you use. By pressing on one of them you’ll be able to preview it and it will be automatically set For more info about how to get the animations, you can look inside the old documentation (3.5 Animations). Spawn position The spawn position for the current map will be created automatically if there is no one. To set spawn position press one of the 3 buttons. The Set to your position button will copy your current position.The Set to looking point button will copy position from your aiming point.The Copy from looking entity button will copy position from the entity you are looking at if there is any. For the manual corrections later see Advanced setup Dialogue setup To create a dialog for the NPC navigate to the Dialogue setup tab For a new dialogue line press the Add new line button. This will add a new panel to the list. Click the panel to edit the dialogue line. Each line will have its own ID displayed. Line with ID 1 will be opened first every time player speaks to the NPC. In the first text box, you can enter NPC’s speech, it supports the newline ( \n ) operator. Inside the Sound: text box you can optionally enter the path to the sound that will be auto-played when the player opens this dialogue line. Example in the video To add more answers that the player can choose, press the Add answer line button on the right. To remove the answer press the Remove answer button. If there are no answers, the “...” answer with the close option will be added automatically. Each answer you create can do two basic things, close the dialogue or open the line with the ID you will choose in the drop-down menu (by pressing on the Action button). If your server uses addons that are supported by “Simple NPCs” you will see the addon’s name in the list. By selecting an addon from the list, the answer will do an action from the addon you chose. To add a playback animation, when you choose an answer (like on this video) you can enter the animation name in the text box after the Action button. To quickly browse all available animations for the model go to the NPC setup tab and use the Get animations button, which will open a list of all animations. Note: The checkbox for use limitation must be checked on (see Use limitations). Tip: For big and complicated dialogues we recommend creating a doc file with dialogue structure before starting setting up the NPCs Final setup Navigate to the Final setup tab, to save NPC preset and copy the Lua code for the NPC. Saving NPC To save the NPC press the Copy NPC Lua code button at the top Then open sh_npcspawn.lua inside mc_simple_npcs/lua/mcs_npcs and paste NPC’s code to the bottom of the file. To replace or remove an existing NPC just select the whole NPC table and remove it. NPCs will automatically spawn on server startup, or you can respawn them by pressing the Respawn all NPCs button or typing the  mcs_npcrespawn command in the console. The Save NPC preset and Open NPC preset buttons will help you to save NPC presets and open them when you need to edit any of the NPCs without editing Lua file. The New NPC preset button will just create a blank NPC. Advanced Setup Note. In advanced setup mostly we will be working with an existing NPC table and you will need lua knowledge to do this correctly. NPC Table structure: MCS.Spawns["uid"] = { // uid - the unique id for an NPC name = "Name", // NPC's name will be shown to players above the NPC and via the dialogue. model = "models/path/npc.mdl", // Path to the model scale = 1, // NPC model scale (size), 1 - normal, 2 - 2 times bigger, 0.5 - 2 times smaller uselimit = false, // Allow only one player to speak to the npc at the same time theme = "Theme Name", // Dialogue theme. Currently supported themes - Default, Retro, Hollow Knight pos = { ["map_name"] = {Vector(0,0,0), Angle(0,0,0)}, // spawn position filter by maps ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // use 'all' to spawn npc any way, even if there is no map in this table }, bgr = { [1] = 2, [2] = 0, }, // Table of bodygroups [The id of the bodygroup you're setting. Starts from 0] = The value you're setting the bodygroup to. Starts from 0 skin = 1, // Sets the skin of the entity namepos = 30, // Use this field to set up the hight position of NPC's name above his head random_dialog = {dialogue id, dialogue id}, // Use this table to start dialogue form a random position (ex.: {1, 3} will randomly start from 1 or 3 dialogue line) sequence = "name of the animation", // id for sequence animation, use table (ex.: {"id1", "id2"}) to play random animation dialogs = { [dialogue id, start from 1] = { ["Line"] = "Text that NPC tells you", ["Sound"] = "Path to sound, keep it empty or nil value if you do not want use any sfx", ["Answers"] = { {"Answer text", id for next line "close" to close the dialogue or { id, id } for random line, callback function , check function, "playback animation"}, }, } } } NPC position customization To spawn your NPC on multiple maps in different locations you must add new value, for each map you need, inside the pos table. The key for the value is the map name, the value itself is a table with NPC’s position and angle. If you want to spawn the NPC on maps that are not in the list use “all” instead of the map name. Note. If you’ll create two or more different spawn positions for one map, only one will work. You cannot spawn the same NPC more than one time on the same map. Example: pos = { ["gm_atomic"] = {Vector(570.41230,760.10539,-3123), Angle(0,90,0)}, // spawn npc on gm_atomic map ["rp_evocity2_v2p"] = {Vector(4213,5345,621), Angle(0,180,0)}, // spawn npc on rp_evocity2_v2p map ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // spawn npc on all other maps }, Skin and Bodygroup setup To set skin, if the model you use features multiple skins, simply add skin = skin_id, the line to the NPC table, where skin_id is your skin's ID number. For the bodygroups - add table bgr = {[1] = 2,[2] = 0,}, Table structure: [The id of the body group you're setting. Starts from 0] = The value you're setting the body group to. Starts from 0 Tip. We recommend using Easy Bodygroup Tool for this Example: Let’s give the clipboard to Dr. Kleiner model = "models/kleiner.mdl", bgr = {[1] = 1}, sequence = "lineidle03", Random animation To make your NPC play random animation every time it spawns, simply create a table for the sequence line. Example: NPC will spawn with one of these 3 animations sequence = {"scaredidle","lineidle02","lineidle01"}, NPC's name adjustment To adjust the height of NPC’s name after the main setup was done, edit namepos = number, line inside the NPC table. This can be useful if you use bigger or smaller models. Example: NPC uses crouch animation and we slide to name a little bit down namepos = 30, Random dialogue start To start a dialogue from a random line you can add this parameter random_dialog = {number id, number id, number id},  to the NPC table, after the main setup was done. When a player starts a dialogue with the NPC, one of the dialogue line ids will be chosen randomly to start as a first line, instead of opening the first one. This can be useful to make dialogues with frequently used NPCs less boring. Example: This will randomly open the first, 2nd, or 5th dialogue as a first one random_dialog = {1, 2, 5}, Random dialogue on the answer To start a random dialogue on a certain answer randomly, you can create a table instead of id for the next line  {number id, number id, number id},. When the player chose this answer, one of the dialogue line ids will be chosen randomly as the next answer. Example: This will randomly open the 4th, 5th, 6th, or 7th dialogue as randomly as an answer ["Answers"] = { {"Tell me a joke!", {4, 5, 6, 7} }, }, Extra functions for the answer table: Сallback function Description: This function called clientside when the player chooses the answer, keep it nil to ignore it. Example 1: Sends a net message to the server ["Answers"] = { {"Show me what you got", "close", function() net.Start(“Open_some_menu”) net.SendToServer() end}, }, Example 2: Ignores callback function while using check function ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, }, Check function( Entity npc ) Description: Clientside function that controls whether to add the answer to the list or not. Must return boolean Arguments: Entity from where this function was called Example 1: Sends a net message to the server ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, {"I’m injured", "close", function() net.Start(“Buy_Health”) net.SendToServer() end, function() return LocalPlayer():Health() < 100 end}, }, Template to choose job via NPC: Change job to Civil Protection via dialogue.Note: If you want to start the vote for changing job, add “vote” before the job command (see line 3) ["Answers"] = { {"I want to become a CP", "close", function() RunConsoleCommand("darkrp", "cp" ) end}, {"I want to be a mayor", "close", function() RunConsoleCommand("darkrp", "votemayor" ) end}, }, Template - Job-resticter answers Shows first line only to Civil Protection job and other for other jobs: ["Answers"] = { {"Hi officer", "close", nil, function() return LocalPlayer():Team() == TEAM_POLICE end}, {"What do you need, bugger", "close", nil, function() return LocalPlayer():Team() ~= TEAM_POLICE end}, }, Old documentation MAC's NPCs v1.2 Documentation (ENG) Basic Setup 1. To install this addon to your server just unzip it to your garrysmod/addons folder 2. Inside “mc_simple_npcs/lua/mcs_npcs” open sh_config.lua and configure the addon Config: MCS.Config.UseDelay = 2 // Delay between player can press "Use" button on NPCs MCS.Config.TextSpeed = 3 // Speed of text typing animation (1 - fastest, 10 - slowest) MCS.Config.DebugMode = false // DebugMode enables close button at top right corner MCS.Config.NPCTextColor = Color(255,255,255) // Color of NPC's text MCS.Config.TextColor = Color(255,255,255) // Color of answers NPC's name and skip button MCS.Config.HighlightColor = Color(217,170,0) // Color of answer button when highlighted MCS.Config.LinesColor = Color(155,155,155) // UI's outline color MCS.Config.HLLinesColor = Color(255,255,255) // UI's corner lines color MCS.Config.EnableBlur = true // Enable UI blur effect MCS.Config.SkipButton = "Press LMB to skip" // Text of skip button MCS.Config.AnswersFont = "MCS_Arial32" // Answer lines font MCS.Config.NPCFont = "MCS_Arial24" // NPC's text font MCS.Config.AnswersAlign = TEXT_ALIGN_LEFT // Answer text align - TEXT_ALIGN_LEFT TEXT_ALIGN_RIGHT TEXT_ALIGN_CENTER 3. To start setting up an NPC enter the server. Open the game console and type the mcs_setup command to open the setup menu. Note: In order to open you must have superadmin privilege on your server This menu will feature some things like autosave on close and autoload last edited NPC and a menu bar with options to load and save current NPC as a template You also can start a fresh setup by choosing New option NPC Setup Unique ID In this text box, you must enter the unique name for the NPC. It used only by the server and it must be unique for each NPC you create. It will also be used as a name for the save file. NPC Name NPC’s Name will be displayed above it and inside the dialogue box. Example: NPC Name position This slider will adjust the height of the NPC’s name displayed above his head. This can be useful if you use bigger or smaller models. Read more about it in the advanced setup Use limitation By checking this option only one player will be able to use the NPC. This is option is needed if you want to use animation playback in the dialog. See more at The Dialogue setup Dialogue theme Here you can change the dialogue UI themes from the list of supported themes. This will affect only the NPC you are editing. Note: Currently supported themes - Default, Retro, Hollow Knight Model and animation setup To set a model for your NPC, copy and paste the path to the model inside the text box. You can preview the model on the side panel, rotate it, and zoom by double clicking it. If your model supports bodygroups or skins you will see the sliders for adjustment. To make your NPC animated, enter the animation name inside the “Animation” text box. By pressing Get Anim. button you’ll see a list of all animations for the model you use. By pressing on one of them you’ll be able to preview it and it will be automatically set For more info about how to get the animations, you can look inside the old documentation (3.5 Animations). Spawn position To add spawn position for each map you want click Add Map button The spawn position for the current map will be created automatically if there is no one. Inside the text box, you can enter or modify the map name. If you want to spawn the NPC on maps that are not in the list use “all” instead of the map name. To edit the spawn position press the Edit button: In the opened menu, you can type spawn vector and angle or press the Player Pos button to copy your own position and the Ent Pos button to get the position of the entity you are looking at. For the manual corrections later see Advanced setup The Dialogue setup For a new dialogue line press the “Add Line” button. This will add a new panel to the list below. Each line will have its own ID displayed in the top left corner. Line with ID 1 will be opened first every time player speaks to the NPC. In the first text box, you can enter NPC’s speech, it supports the newline ( \n ) operator. Inside the “Sound:” text box you can optionally enter the path to the sound that will be auto-played when the player opens this dialogue line. Example in the video To add more answers that the player can choose, press the “Add Answer” button. To remove the answer press the “Del” button. If there are no answers, the “...” answer with the close option will be added automatically. Each answer you create can do two basic things, close the dialogue or open the line with the ID you will choose in the drop-down menu (by pressing on the close button). If your server uses addons that are supported by “Simple NPCs” you will see the addon’s name in the list. By selecting an addon from the list, the answer will open the menu from the addon you chose. To add a playback animation, when you choose an answer (like on this video) you can enter the animation name in the text box after the Del. button. To quickly browse all available animations for the model press Get. Anim. button, which will open a list of all animations. Note: The checkbox for use limitation must be checked on (see step 4.4 ). Tip: For big and complicated dialogues we recommend creating a doc file with dialogue structure before starting setting up the NPCs You can quickly test the dialog by pressing the “Test the dialogs” button. Helpful for big and complicated dialogues Saving NPC To save the NPC press the “Copy to Clipboard and Close” button at the bottom or choosing the “Copy Lua code” option from the Edit menu on the menu bar. Then open sh_npcspawn.lua inside “MC Simple NPCs/lua/mcs_npcs” and paste NPC’s code to the files bottom. To replace or remove an existing NPC just select the whole NPC table and remove it. NPCs will automatically spawn on server startup, or you can respawn them by typing the mcs_npcrespawn command in the console. Advanced Setup Note. In advanced setup mostly we will be working with an existing NPC table and you will need lua knowledge to do this correctly. NPC Table structure: MCS.Spawns["uid"] = { // uid - the unique id for an NPC name = "Name", // NPC's name will be shown to players above the NPC and via the dialogue. model = "models/path/npc.mdl", // Path to the model uselimit = false, // Allow only one player to speak to the npc at the same time theme = "Theme Name", // Dialogue theme. Currently supported themes - Default, Retro, Hollow Knight pos = { ["map_name"] = {Vector(0,0,0), Angle(0,0,0)}, // spawn position filter by maps ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // use 'all' to spawn npc any way, even if there is no map in this table }, bgr = { [1] = 2, [2] = 0, }, // Table of bodygroups [The id of the bodygroup you're setting. Starts from 0] = The value you're setting the bodygroup to. Starts from 0 skin = 1, // Sets the skin of the entity namepos = 30, // Use this field to set up the hight position of NPC's name above his head random_dialog = {dialogue id, dialogue id}, // Use this table to start dialogue form a random position (ex.: {1, 3} will randomly start from 1 or 3 dialogue line) sequence = "name of the animation", // id for sequence animation, use table (ex.: {"id1", "id2"}) to play random animation dialogs = { [dialogue id, start from 1] = { ["Line"] = "Text that NPC tells you", ["Sound"] = "Path to sound, keep it empty or nil value if you do not want use any sfx", ["Answers"] = { {"Answer text", id for next line, "close" to close the dialogue, or { id, id } for random line, callback function , check function, "playback animation"}, }, } } } NPC position customization To spawn your NPC on multiple maps in different locations you must add new value, for each map you need, inside the pos table. The key for the value is the map name, the value itself is a table with NPC’s position and angle. If you want to spawn the NPC on maps that are not in the list use “all” instead of the map name. Note. If you’ll create two or more different spawn positions for one map, only one will work. You cannot spawn the same NPC more than one time on the same map. Example: pos = { ["gm_atomic"] = {Vector(570.41230,760.10539,-3123), Angle(0,90,0)}, // spawn npc on gm_atomic map ["rp_evocity2_v2p"] = {Vector(4213,5345,621), Angle(0,180,0)}, // spawn npc on rp_evocity2_v2p map ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // spawn npc on all other maps }, Skin and Bodygroup setup To set skin, if the model you use features multiple skins, simply add skin = skin_id, the line to the NPC table, where skin_id is your skin's ID number. For the bodygroups - add table bgr = {[1] = 2,[2] = 0,}, Table structure: [The id of the body group you're setting. Starts from 0] = The value you're setting the body group to. Starts from 0 Tip. We recommend using Easy Bodygroup Tool for this Example: Let’s give the clipboard to Dr. Kleiner model = "models/kleiner.mdl", bgr = {[1] = 1}, sequence = "lineidle03", Random animation To make your NPC play random animation every time it spawns, simply create a table for the sequence line. Example: NPC will spawn with one of these 3 animations sequence = {"scaredidle","lineidle02","lineidle01"}, NPC's name adjustment To adjust the height of NPC’s name after the main setup was done, edit namepos = number, line inside the NPC table. This can be useful if you use bigger or smaller models. Example: NPC uses crouch animation and we slide to name a little bit down namepos = 30, Random dialogue start To start a dialogue from a random line you can add this parameter random_dialog = {number id, number id, number id},  to the NPC table, after the main setup was done. When a player starts a dialogue with the NPC, one of the dialogue line ids will be chosen randomly to start as a first line, instead of opening the first one. This can be useful to make dialogues with frequently used NPCs less boring. Example: This will randomly open the first, 2nd, or 5th dialogue as a first one random_dialog = {1, 2, 5}, Random dialogue on the answer To start a random dialogue on a certain answer randomly, you can create a table instead of id for the next line  {number id, number id, number id},. When the player chose this answer, one of the dialogue line ids will be chosen randomly as the next answer. Example: This will randomly open the 4th, 5th, 6th, or 7th dialogue as randomly as an answer ["Answers"] = { {"Tell me a joke!", {4, 5, 6, 7} }, }, Extra functions for the answer table: Сallback function Description: This function called clientside when the player chooses the answer, keep it nil to ignore it. Example 1: Sends a net message to the server ["Answers"] = { {"Show me what you got", "close", function() net.Start(“Open_some_menu”) net.SendToServer() end}, }, Example 2: Ignores callback function while using check function ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, }, Check function( Entity npc ) Description: Clientside function that controls whether to add the answer to the list or not. Must return boolean Arguments: Entity from where this function was called Example 1: Sends a net message to the server ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, {"I’m injured", "close", function() net.Start(“Buy_Health”) net.SendToServer() end, function() return LocalPlayer():Health() < 100 end}, }, Template to choose job via NPC: Change job to Civil Protection via dialogue.Note: If you want to start the vote for changing job, add “vote” before the job command (see line 3) ["Answers"] = { {"I want to become a CP", "close", function() RunConsoleCommand("darkrp", "cp" ) end}, {"I want to be a mayor", "close", function() RunConsoleCommand("darkrp", "votemayor" ) end}, }, MAC's NPCs v1.2 Documentation (RUS) Основные настройки 1. Чтобы установить это дополнение на свой сервер, просто разархивируйте его в папку garrysmod/addons вашего сервера 2. В папке “MC Simple NPCs/lua/mcs_npcs” откройте sh_config.lua для настройки дополнения Конфиг: MCS.Config.UseDelay = 2 // Задержка между нажатиями кнопки "Использовать" на NPC MCS.Config.TextSpeed = 3 // Скорость анимации набора текста (1 - самая быстрая, 10 - самая медленная) MCS.Config.DebugMode = false // DebugMode включает кнопки закрытия меню диалога в правом верхнем углу MCS.Config.NPCTextColor = Color(255,255,255) // Цвет текста NPC's MCS.Config.TextColor = Color(255,255,255) // Цвет текста ответа и кнопки пропуска MCS.Config.HighlightColor = Color(217,170,0) // Цвет текста ответа при выборе MCS.Config.LinesColor = Color(155,155,155) // Цвет контура интерфейса MCS.Config.HLLinesColor = Color(255,255,255) // Цвет углов интерфейса MCS.Config.EnableBlur = true // Эффект размытия интерфейса MCS.Config.SkipButton = "Press LMB to skip" // Текст кнопки пропуска MCS.Config.AnswersFont = "MCS_Arial32" // Шрифт строк ответа MCS.Config.NPCFont = "MCS_Arial24" // Шрифт строк NPC MCS.Config.AnswersAlign = TEXT_ALIGN_LEFT // Направление текста ответа - TEXT_ALIGN_LEFT TEXT_ALIGN_RIGHT TEXT_ALIGN_CENTER 3. Чтобы начать настройку NPC, войдите на сервер. Откройте консоль разработчика и введите команду mcs_setup чтобы открыть меню настройки. Примечание: Вам необходимо иметь права суперадминистратора на вашем сервере чтобы открыть меню настройки. Данное меню имеет такие функции, как автосохранение при закрытии и автосохранение последнего настраиваемого NPC, строку меню с опцией загрузки и сохранения текущего NPC как шаблона. Также Вы можете начать новый проект, выбрав опцию New Настройка NPC Уникальный ID В данном текстовом поле Вы должны ввести уникальное название для NPC. Каждое название должно быть уникальным для данного сервера. Они также будут использоваться в файле сохранения. Имя NPC Имя NPC будет отображаться над его головой и в окне диалога. Пример: Расположение имени NPC Вышеуказанный ползунок регулирует высоту имени NPC у него над головой. Полезна при использовании моделей нестандартного роста. Больше информации в разделе расширенная настройка Ограничение использования Поставив флажок, только один игрок одновременно может использовать NPC. Эта опция необходима, если Вы хотите использовать анимацию в диалоге. Больше информации в разделе Настройка диалога Тема диалога Тут Вы можете выбрать тему интерфейса для диалогов из списка поддерживаемых. Данная опция применяется только на NPC, с которым Вы работаете в данный момент. Примечание: Поддерживаемые темы на данный момент - Default, Retro, Hollow Knight Установка модели и анимации Чтобы выбрать модель для NPC, скопируйте и вставьте путь до модели в поле. Предпросмотр модели находится на боковой панели, для поворота и увеличения сделайте двойной клик по модели. Если выбранная модель поддерживает бодигруппы или скины, то вы увидите ползунки для настройки. To make your NPC animated, enter the animation name inside the “Animation” text box. Чтобы добавить анимацию, введите название анимации в поле “Animation”. Нажав кнопку Get Anim. Вы увидите список всех анимаций для модели, которую Вы используете. По нажатию на одну из них вы сможете её посмотреть и она будет автоматически выбрана. Больше информации про анимации Вы можете найти здесь: old documentation (3.5 Animations). Позиция спавна Чтобы добавить позицию спавна для каждой карты, нажмите Add Map. Позиция спавна будет для текущей карты будет добавлена автоматически, если ранее её не существовало. В текстовом поле Вы можете ввести или изменить название карты. Чтобы установить спавн для карт, которых нет в списке, нажмите “all” вместо названия карты. Чтобы изменить место спавна, нажмите кнопку Edit: В открывшемся меню Вы можете настроить вектор и угол спавна, нажать Player Pos чтобы скопировать свою позицию, или Ent Pos чтобы скопировать позицию предмета, на который Вы смотрите. Для более точной настройки смотрите Расширенная настройка Настройка диалога Для добавления строки диалога нажмите “Add Line”.Это добавит новую панель к списку ниже. Каждая линия диалога имеет ID, который указан в левом верхнем углу. Диалог с номером ID 1 будет проигрываться первый каждый раз, когда игрок начинает разговор с NPC. В первое текстовое поле вписывается реплика NPC, которая поддерживает оператора новой строки ( \n ) В поле “Sound:” по желанию укажите путь к звуку, который будет проигрываться при начатии диалога. Пример в этом видео Для добавления дополнительных ответов, нажмите “Add Answer”. Для удаления - кнопку “Del”. В случае отсутствия вариантов ответов для диалога, ответ “...” с последующим закрытие разговора будет добавлен автоматически. Каждый ответ может иметь одну из двух функций: закончить разговор или открыть новую диалоговую линию с ID, которую вы выберете в выпадающем меню (при нажатии на кнопку закрытия). Если Ваш сервер использует аддоны, поддерживающие “Simple NPCs”, то Вы увидите их в списке. Выбрав аддон из списка, ответ на реплику откроет меню выбранного аддона.. Чтобы добавить анимацию, когда Вы выбираете ответ (как на этом видео) введите название анимации в текстовое поле после кнопки Del. Для быстрого просмотра всех анимаций для модели нажмите кнопку Get. Anim., которая открывает список анимаций. Примечание: Флажок ограничения использования должен быть активирован (смотрите пункт 4.4 ). Совет: Для длинных и сложных диалогов мы советую создать doc файл со структурой диалога перед началом настройки NPC’ов Вы можете протестировать диалог, нажав кнопку “Test the dialogs”. Полезно для сложных диалогов. Сохранение NPC Для сохранение NPC нажмите “Copy to Clipboard and Close” внизу или выберите опцию “Copy lua code” в меню Edit на строке меню. Затем откройте sh_npcspawn.lua внутри “MC Simple NPCs/lua/mcs_npcs” и вставьте скопированный текст в конец документа Для замены или удаления уже существующего NPC просто выделите таблицу этого NPC и удалите её. NPC’ы автоматически появятся при запуске сервера, Или Вы можете заспавнить их вручную, написав mcs_npcrespawn в консоли разработчика. Расширенная настройка Заметка. В расширенной настройке мы будем работать с существующей таблицей NPC, и вам понадобятся знания lua, чтобы сделать это правильно Структура таблицы NPC: MCS.Spawns["uid"] = { // uid - уникальный идентификатор для NPC name = "Name", // Имя NPC будет показано игрокам над NPC и через диалог model = "models/path/npc.mdl", // Путь к модели uselimit = false, // Позволяет только одному игроку использовать NPC в данный момент theme = "Theme Name", // Тема диалога. Поддерживаемые темы на данный момент - Default, Retro, Hollow Knight pos = { ["map_name"] = {Vector(0,0,0), Angle(0,0,0)}, // фильтр позиции спавна по картам ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // Используйте 'all' для спавна npc, даже если в этой таблице нет карты }, bgr = { [1] = 2, [2] = 0, }, // Таблица бодигрупп [ID бодигрупп . Начинается с 0] = Значение бодигруппы. Начинается с 0 skin = 1, // Устанавливает скин для NPC namepos = 30, // Используйте это поле, чтобы установить высоту положения имени NPC над его головой sequence = "name of the animation", // id анимации, используйте таблицу (прм.: {"id1", "id2"}) для воспроизведения случайной анимации random_dialog = {dialogue id, dialogue id}, // Используйте эту таблицу чтобы начать диалог со случайного, из списка (прм: {1, 3} начнет диалог случайно либо с 1, либо с 3 диалога) dialogs = { [id диалога, начинается с 1] = { ["Line"] = "Текст, который NPC говорит игроку", ["Sound"] = "Путь к звуку. Оставьте его пустым, если Вы не хотите использовать звук", ["Answers"] = { {"Текст ответа", id для следующей строки, "close" чтобы закрыть диалог или таблицу { id, id } для случайного диалога, функция возврата function , функция проверки function }, }, } } } Настройка позиции NPC Чтобы создать своего NPC на нескольких картах в разных местах, Вы должны добавить новое значение для каждой карты в таблице pos. Ключом к значению является имя карты, само значение - это таблица с позицией и углом NPC. Если Вы хотите создать NPC на картах, которых нет в списке, используйте “all” вместо имени карты. Заметка. Если Вы создадите две или более разных позиций появления для одной карты, будет работать только одна. Вы не сможете создать одного и того же NPC в нескольких местах на одной карте. Пример: pos = { ["gm_atomic"] = {Vector(570.41230,760.10539,-3123), Angle(0,90,0)}, // создает NPC на карте gm_atomic ["rp_evocity2_v2p"] = {Vector(4213,5345,621), Angle(0,180,0)}, // создает NPC на карте rp_evocity2_v2p ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // создает NPC на всех остальных картах }, Настройка скина и “бодигрупп” Чтобы установить скин, если используемая модель имеет несколько скинов, просто добавьте skin = skin_id, строку к таблице NPC, где skin_id это номер вашего скина. Для “бодигрупп” - добавить таблицу bgr = {[1] = 2,[2] = 0,}, Структура таблици: [Идентификатор bodygroup, которую вы устанавливаете. Начинается с  0] =Значение, которое вы устанавливаете для bodygroup. Начинается с 0 Заметка. Мы рекомендую использовать Easy Bodygroup Tool для быстрой настройки Пример: Давайте дадим клипборд Др. Кляйнеру model = "models/kleiner.mdl", bgr = {[1] = 1}, sequence = "lineidle03", Случайная анимация Чтобы ваш NPC проигрывал случайную анимацию каждый раз, когда он появляется, просто создайте таблицу на строчке sequence. Пример: NPC будет появляться с одной из этих 3 анимаций sequence = {"scaredidle","lineidle02","lineidle01"}, Корректировка имени NPC Чтобы настроить высоту имени над NPC, добавьте namepos = number, строчку в таблицу с NPC. Это может быть полезно, если вы используете большие или маленькие модели. Пример: NPC использует анимацию приседания, и мы немного сдвигаем имя namepos = 30, Начало случайного диалога Чтобы начать диалог со случайного предложения Вы можете добавить параметр random_dialog = {номер id, номер id, номер id},  в таблицу NPC после того, как закончите основную настройку. Когда игрок начинает диалог с NPC, В случайном порядке выбирается ID предложения для начала диалога вместо использования первого предложения в установленном порядке. Полезно для вариативности часто используемых NPC. Пример: Параметр случайно выберет первое, второе или пятое предложение на место первого random_dialog = {1, 2, 5}, Случайный диалог после ответа Чтобы начать случайный диалог после конкретных ответов, Вы можете сделать таблицу вместо написания ID следующего предложения  {номер id, номер id, номер id},. Когда игрок выбрал этот ответ, случайный ID из списка будет выбран как ответ.. Пример: Параметр случайно выберет 4ое, 5ое, 6ое, или 7ое предложение как ответ ["Answers"] = { {"Tell me a joke!", {4, 5, 6, 7} }, }, Дополнительные функции для таблицы ответов: Функция возврата Описание: Эта функция вызывается на стороне клиента, когда игрок выбирает ответ, выставите значение nil, чтобы игнорировать ее. Пример 1: Отправляет сетевое сообщение на сервер ["Answers"] = { {"Show me what you got", "close", function() net.Start(“Open_some_menu”) net.SendToServer() end}, }, Пример 2: Игнорирует функцию обратного вызова при использовании функции проверки ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, }, Функция проверки ( Entity npc ) Описание: Клиентская функция, которая управляет добавлением ответа в список или нет. Должена возвращать логическое значение Аргументы: Объект откуда эта функция была вызвана Пример 1: Отправляет сетевое сообщение на сервер при условии если у игрока меньше 100 здоровья ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, {"I’m injured", "close", function() net.Start(“Buy_Health”) net.SendToServer() end, function() return LocalPlayer():Health() < 100 end}, }, Шаблон для выбора работы через NPC: Меняет работу на “Гражданскую оборону”.Заметка: Если вы хотите начать голосование за смену должности, добавьте “vote” перед командой работы (см.строку 3) ["Answers"] = { {"I want to become a CP", "close", function() RunConsoleCommand("darkrp", "cp" ) end}, {"I want to be a mayor", "close", function() RunConsoleCommand("darkrp", "votemayor" ) end}, }, MAC's NPCs v1.2 Documentation (ESP) Configuración básica 1. Para instalar este complemento en su servidor simplemente descomprímalo en su carpeta garrysmod / addons 2. Dentro de "mc_simple_npcs/lua/mcs_npcs" abra sh_config.lua y configure el complemento Config: MCS.Config.UseDelay = 2 // Задержка между нажатиями кнопки "Использовать" на NPC MCS.Config.TextSpeed = 3 // Скорость анимации набора текста (1 - самая быстрая, 10 - самая медленная) MCS.Config.DebugMode = false // DebugMode включает кнопки закрытия меню диалога в правом верхнем углу MCS.Config.NPCTextColor = Color(255,255,255) // Цвет текста NPC's MCS.Config.TextColor = Color(255,255,255) // Цвет текста ответа и кнопки пропуска MCS.Config.HighlightColor = Color(217,170,0) // Цвет текста ответа при выборе MCS.Config.LinesColor = Color(155,155,155) // Цвет контура интерфейса MCS.Config.HLLinesColor = Color(255,255,255) // Цвет углов интерфейса MCS.Config.EnableBlur = true // Эффект размытия интерфейса MCS.Config.SkipButton = "Press LMB to skip" // Текст кнопки пропуска MCS.Config.AnswersFont = "MCS_Arial32" // Шрифт строк ответа MCS.Config.NPCFont = "MCS_Arial24" // Шрифт строк NPC MCS.Config.AnswersAlign = TEXT_ALIGN_LEFT // Направление текста ответа - TEXT_ALIGN_LEFT TEXT_ALIGN_RIGHT TEXT_ALIGN_CENTER 3. Para comenzar a configurar un NPC, ingrese al servidor. Abra la consola de juegos y escriba el comando mcs_setup para abrir el menú de configuración. Nota: para abrir debe tener privilegio superadmin en su servidor Este menú presentará algunas cosas como, guardar automáticamente al cerrar y cargar automáticamente el último NPC editado y una barra de menú con opciones para cargar y guardar el NPC actual como plantilla También puede comenzar una nueva configuración seleccionando New opción Configuración de NPC Nombre único En este cuadro de texto, debe ingresar el nombre único para el NPC. Solo lo usa el servidor y debe ser único para cada NPC que cree. También se usará como nombre para guardar el archivo. Nombre de NPC El nombre del NPC se mostrará encima y dentro del cuadro de diálogo. Ejemplo: Posición del nombre del NPC Este control deslizante ajustará la altura del nombre del NPC que se muestra sobre su cabeza. Esto puede ser útil si usa modelos más grandes o más pequeños. Lea más sobre esto en la configuración avanzada Limitación de uso Al marcar esta opción, solo un jugador podrá usar el npc. Esta opción es necesaria si desea utilizar la reproducción de animación en el cuadro de diálogo. Ver más en 4.8 La configuración de Diálogo Tema de diálogo Aquí puede cambiar el tema de la interfaz de usuario del diálogo de la lista de temas compatibles. Esto afectará solo el npc que está editando. Nota: Temas soportados actualmente - Predeterminado, Retro, Hollow Knight Configuración de modelo y animación Para establecer un modelo para su NPC, copie y pegue la ruta al modelo dentro del cuadro de texto. Puede obtener una vista previa del modelo en el panel lateral, rotarlo y hacer zoom haciendo doble clic en él. Si su modelo admite grupos de Para animar su NPC, ingrese el nombre de la animación dentro del cuadro de texto "Animación". Al presionar Get Anim. verá una lista de todas las animaciones para el modelo que usa. Al presionar uno de ellos, podrá obtener una vista previa y se configurará automáticamente Para obtener más información sobre cómo obtener las animaciones, puede mirar dentro del Posición de desove Para agregar la posición de generación para cada mapa que desee, haga clic en el botón Add Map. La posición de generación para el mapa actual se creará automáticamente si no hay nadie. Dentro del cuadro de texto puede ingresar o modificar el nombre del mapa. Si desea generar el NPC en mapas que no están en la lista, use "todos" en lugar del nombre del mapa. Para editar la posición de generación, presione el botón Editar: En el menú abierto, puede escribir el vector de generación y el ángulo o presionar el botón Player Pos para copiar su propia posición y el botón Ent Pos para obtener la posición de la entidad que está mirando. Para las correcciones manuales posteriores, ver configuración avanzada La configuración del diálogo Para una nueva línea de diálogo, presione el botón "Agregar línea". Esto agregará un nuevo panel a la lista a continuación. Cada línea tendrá su propia ID que se mostrará en la esquina superior izquierda. La línea con ID 1 se abrirá primero cada vez que el jugador hable con el NPC. En el primer cuadro de texto, puede ingresar el discurso de NPC, es compatible con el operador de nueva línea (\ n). Dentro del cuadro de texto "Sonido:" puede ingresar opcionalmente la ruta al sonido que se reproducirá automáticamente cuando el jugador abra esta línea de diálogo. Ejemplo en el video Para agregar más respuestas que el jugador pueda elegir, presione el botón "Agregar respuesta". Para eliminar la respuesta, presione el botón "Del". Si no hay ninguna respuesta, la respuesta "..." con opción de cierre se agregará automáticamente. Cada respuesta que cree puede hacer dos cosas básicas, cerrar el diálogo o abrir la línea con la ID que elegirá en el menú desplegable (presionando el botón Cerrar). Si su servidor utiliza complementos compatibles con "NPC simples", verá el nombre del complemento en la lista. Al seleccionar un complemento de la lista, la respuesta abrirá el menú del complemento que elija. Para agregar una animación de reproducción, cuando elige una respuesta (como en este video) puede ingresar el nombre de la animación en el cuadro de texto después del botón Supr. Para explorar rápidamente todas las animaciones disponibles para el modelo, presione Obtener. Anim. botón, que abrirá una lista de todas las animaciones. Nota: La casilla de verificación de limitación de uso debe estar activada (consulte el paso 4.4). Consejo: para diálogos grandes y complicados, recomiendo crear un archivo doc con estructura de diálogo antes de comenzar a configurar los NPC Puede probar rápidamente el diálogo presionando el botón "Probar los diálogos". Útil para diálogos grandes y complicados. Guardar NPC Para guardar el NPC presione el botón "Copiar al portapapeles y cerrar" en la parte inferior o seleccione la opción "Copiar código lua" en el menú Editar en la barra de menú.                       Luego abra sh_npcspawn.lua dentro de "MC Simple NPCs / lua / mcs_npcs" y pegue el código de NPC en la parte inferior de los archivos. Para reemplazar o eliminar un NPC existente, simplemente seleccione la tabla NPC completa y elimínela. Los NPC se generarán automáticamente al iniciar el servidor, o puede reaparecerlos escribiendo el comando mcs_npcrespawn en la consola. cuerpo o máscaras, verá los controles deslizantes para el ajuste. Configuración avanzada Nota. En la configuración avanzada, trabajaremos principalmente con una tabla NPC existente y necesitará conocimientos de lua para hacerlo correctamente. Estructura de la tabla de NPC: MCS.Spawns["uid"] = { // uid - the unique id for an NPC name = "Name", // NPC's name will be shown to players above the NPC and via the dialogue. model = "models/path/npc.mdl", // Path to the model uselimit = false, // Allow only one player to speak to the npc at the same time theme = "Theme Name", // Dialogue theme. Currently supported themes - Default, Retro, Hollow Knight pos = { ["map_name"] = {Vector(0,0,0), Angle(0,0,0)}, // spawn position filter by maps ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // use 'all' to spawn npc any way, even if there is no map in this table }, bgr = { [1] = 2, [2] = 0, }, // Table of bodygroups [The id of the bodygroup you're setting. Starts from 0] = The value you're setting the bodygroup to. Starts from 0 skin = 1, // Sets the skin of the entity namepos = 30, // Use this field to set up the hight position of NPC's name above his head random_dialog = {dialogue id, dialogue id}, // Use this table to start dialogue form a random position (ex.: {1, 3} will randomly start from 1 or 3 dialogue line) sequence = "name of the animation", // id for sequence animation, use table (ex.: {"id1", "id2"}) to play random animation dialogs = { [dialogue id, start from 1] = { ["Line"] = "Text that NPC tells you", ["Sound"] = "Path to sound, keep it empty or nil value if you do not want use any sfx", ["Answers"] = { {"Answer text", id for next line, "close" to close the dialogue, or { id, id } for random line, callback function , check function, "playback animation"}, }, } } } Personalización de posición de NPC Para generar su NPC en múltiples mapas en diferentes ubicaciones, debe agregar un nuevo valor, para cada mapa que necesite, dentro de la tabla de pos. La clave para el valor es el nombre del mapa, el valor en sí es una tabla con la posición y el ángulo del NPC. Si desea generar el NPC en mapas que no están en la lista, use "todos" en lugar del nombre del mapa. Nota. Si va a crear dos o más posiciones de generación diferentes para un mapa, solo una funcionará. No puede generar el mismo npc más de una vez en el mismo mapa. Ejemplo: pos = { ["gm_atomic"] = {Vector(570.41230,760.10539,-3123), Angle(0,90,0)}, // spawn npc on gm_atomic map ["rp_evocity2_v2p"] = {Vector(4213,5345,621), Angle(0,180,0)}, // spawn npc on rp_evocity2_v2p map ["all"] = {Vector(0,0,0), Angle(0,0,0)}, // spawn npc on all other maps }, Configuración de skin y bodygroup Para establecer la piel, si el modelo que usa presenta varias piel, simplemente agregue skin = skin_id, línea a la tabla NPC, donde skin_id es el número de ID de su máscara. Para los grupos del cuerpo: agregue la tabla bgr = {[1] = 2, [2] = 0,}, Estructura de la tabla: [La identificación del grupo del cuerpo que está configurando. Comienza desde 0] = El valor en el que está configurando el grupo de cuerpo. Comienza desde 0 Propina. Recomiendo usar Easy Bodygroup Tool para esto Example: Démosle el portapapeles al Dr. Kleiner model = "models/kleiner.mdl", bgr = {[1] = 1}, sequence = "lineidle03", Animación al azar Para hacer que tu NPC reproduzca una animación aleatoria cada vez que se genera, simplemente crea una tabla para la línea de secuencia. Example: El NPC aparecerá con una de estas 3 animaciones. sequence = {"scaredidle","lineidle02","lineidle01"}, Ajuste de nombre de NPC Para ajustar la altura del nombre del NPC después de que se realizó la configuración principal, edite namepos = number, línea dentro de la tabla NPC. Esto puede ser útil si usa modelos más grandes o más pequeños. Ejemplo: El NPC usa animación agachada y deslizamos el nombre un poco hacia abajo namepos = 30, Inicio de diálogo aleatorio Para iniciar el diálogo desde una línea aleatoria, puede agregar este parámetro random_dialog = {number id, number id, number id}, a la tabla npc, después de realizar la configuración principal. Cuando el jugador inicia un diálogo con el npc, uno de los identificadores de línea de diálogo se elegirá aleatoriamente para comenzar como primera línea, en lugar de abrir el primero. Esto puede ser útil para hacer que los diálogos con npcs de uso frecuente sean menos aburridos. Ejemplo: Esto abrirá aleatoriamente el primer, segundo o quinto diálogo como el primero random_dialog = {1, 2, 5}, Diálogo aleatorio sobre respuesta Para iniciar un diálogo aleatorio sobre cierta respuesta al azar, puede crear una tabla en lugar de una identificación para la siguiente línea. Cuando el jugador elige esta respuesta, uno de los identificadores de la línea de diálogo se elegirá aleatoriamente como la siguiente respuesta. Ejemplo: Esto abrirá aleatoriamente el 4º, 5º, 6º o 7º diálogo tan aleatoriamente como una respuesta ["Answers"] = { {"Tell me a joke!", {4, 5, 6, 7} }, }, Funciones adicionales para la tabla de respuestas: Función de respaldo Descripción: Esta función se llama el cliente cuando el jugador elige la respuesta, manténgala nula para ignorarla. Ejemplo 1: Envía un mensaje neto al servidor ["Answers"] = { {"Show me what you got", "close", function() net.Start(“Open_some_menu”) net.SendToServer() end}, }, Ejemplo 2 Ignora la función de devolución de llamada mientras usa la función de verificación ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, }, Función de verificación (Entidad npc) Descripción: función del lado del cliente que controla si se agrega la respuesta a la lista o no. Debe devolver boolean Argumentos: entidad desde donde se llamó esta función Ejemplo 1: Envía un mensaje neto al servidor ["Answers"] = { {"I’m fine", "close", nil ,function() return LocalPlayer():Health() >= 100 end}, {"I’m injured", "close", function() net.Start(“Buy_Health”) net.SendToServer() end, function() return LocalPlayer():Health() < 100 end}, }, Plantilla para elegir trabajo a través de NPC: Cambiar de trabajo a Protección Civil a través del diálogo. Nota: Si desea comenzar a votar para cambiar de trabajo, agregue "votar" antes del comando de trabajo (consulte la línea 3) ["Answers"] = { {"I want to become a CP", "close", function() RunConsoleCommand("darkrp", "cp" ) end}, {"I want to be a mayor", "close", function() RunConsoleCommand("darkrp", "votemayor" ) end}, },