Скриптование - Страница 352 - Скрипты / конфиги / движок - AMK Team
Перейти к контенту

Рекомендуемые сообщения

Тема для обсуждения скриптов всего и всех в серии игр STALKER.


Задавая вопрос (!):
1. Внимательно изучите суть вопроса. Вопрос должен соответствовать выбранной Вами темы. Это поможет сохранить порядок и читабельность темы, а также облегчит поиск и понимание сего;
2. Изучите то, что уже есть в теме (пролистайте "руками", воспользуйтесь поиском на форуме);
3. Изучите информацию которая может вам помочь:

 
 

Stalkerin. Там есть много хороших статей касательно данной темы.
Уроки по модостроению. Есть рабочие примеры готовых скриптов различного назначения.

 

Справочное руководство по языку Lua 5.1
https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual/ru
Справочник по функциям и классам. Собрано много информации по функциям и классам, не всем, но по основные сведения предоставлены.

4. Дабы не превращать обсуждение в "кашу" разной информативной направленности, задавайте несколько вопросов по порядку (в разных постах) после того, как получите ответ на предыдущий вопрос;
5. "Спасибо" и тому подобное - будьте так любезны в ПМ. Если не любите писать в ПМ, в конце вопроса напишите фразу: "Заранее спасибо!" - или что-то в этом духе;
6. ПОЖАЛУЙСТА! Указывайте, для какой игры Вам необходима информация (ТЧ, ЧН, ЗП), если стоит мод - укажите название мода;
7. Если Вы что-то сделали и результат не такой, какой Вами задумывался, то, пожалуйста, приводите коды которые Вы изменяли/писали целиком! Это поможет другим правильно ответить на Ваш вопрос, а также оградит Вас от лишней писанины.
8. Оформляйте сообщение. Пользуйтесь тегами для того, чтобы отделить код от текста. Пишите грамотно - ПОЛЬЗУЙТЕСЬ ЗНАКАМИ ПРЕПИНАНИЯ.
9. И помните: «Правильно заданный вопрос – половина ответа».

 

Какие вопросы следует задавать, а какие нет...

 

Задавайте вопросы, которые касаются непосредственно скриптов и их работы, т.е. Вы что-то делаете, а у Вас что-то не получается, при этом у Вас на руках должен быть хотя бы какой-то код, свидетельствующий о Вашей причастности к вопросу.

 

Вопросы которые будут удалятся, следовательно их задавать не нужно:
-- Где находится та или иная функция?
Для ответа используем поиск по словам среди файлов оригинальной игры или мода, если объект поиска относится к нему, при помощью программы, которая Вам наиболее симпатизирует;
-- Как сделать что-то/то-то?
С подобными вопросами, либо в "ковырялки", где Вам вероятнее всего так же не ответят, либо выдвигаем мысли, подкреплённые теорией, практикой (идеальный вариант) и здравым рассудком;
-- Вопросы со смыслом: "сделайте", "совместите" и подобными глаголами повелительного наклонения.
-- К тому же удалению будут подвергаться вопросы, в которых масштабно не используются теги, для отделения кода и цитат от основного текста, а также не вписан в спойлер код размером превышающие семь строк.
Ответ на возможно возникший вопрос: В какую тему можно обратиться по поводу логики и спавна объектов?
В тему "ковырялок" соответствующей версии игры, для которой Вы задаёте вопрос.

И последнее: очень рекомендовано к прочтению Правила форума
 


  • Спасибо 1
  • Полезно 2
Ссылка на комментарий
https://www.amk-team.ru/forum/topic/6185-skriptovanie/

из amk.script (1.4.1) связанная пара name/id для универсальности... пробуй...

--удаляем предмет из инвентаря по имени
function remove_item_from_inventory_by_name(remove_item_name,npc)
  return remove_item_from_inventory(npc:object(remove_item_name),npc)
end

--удаляем предмет из инвентаря по id
function remove_item_from_inventory(remove_item,npc)
  if npc==nil then npc=db.actor end -- если npc не указан, будет работать с инвентарем ГГ
  if remove_item~=nil then
    alife():release(alife():object(remove_item:id()), true)
    return true
  end
  return false
end

  • Спасибо 1

Есть ли возможность при спавне предмета в инвентарь НПС сразу получить game_object предмета?

Что значит - "сразу" ?

В онлайн любой объект входит тогда, когда до него "дойдут руки".

 

Делайте отложенную проверку, типа

 

 

 

local t_outfit_cnd

function set_item_condition( t )
    local t, n = {}, 0
    local item
    for i, v in pairs( t_outfit_cnd ) do
        item = lobj_by_id( v[1] )
        if item then item:set_condition( v[2] / 100 )
        else n = n + 1; t[n] = v
    end    end
    if n ~= 0 then t_outfit_cnd = t
    else
        t_outfit_cnd = false
        bind_stalker.task_del( "death_manager.set_item_condition", 1000 )
    end
end
 
...
if t_outfit_cnd then
 t_outfit_cnd[#t_outfit_cnd + 1] =
 { obj.id, math_random( cnd_min, cnd_max ) }
else
 t_outfit_cnd = { { obj.id, math_random( cnd_min, cnd_max ) } }
 bind_stalker.task_add( "death_manager.set_item_condition", 1000, set_item_condition )
end

где task_add()/task_del() - добавление/удаление функции в апдейт

 

 

Изменено пользователем Dennis_Chikin

Сразу - не имеется ввиду в тот же момент на апдейте, просто, допустим, при спавне в таблицу вносится запись вида "секция_предмета_ид_предмета" = game_object, вот такой спавн меня интересует, как это можно сделать?)

@kmsk, на вскидку, в качестве идеи. Отлавливаем появление патронов в инвентаре в on_take. Пробегаемся по инвентарю и ищем стволы, у которых с прошлого раза не стало патронов. Не самое оптимальное решение, но это всего лишь идея.

Скажите почему когда я добавил динамические аномалии, то при старте игры сильно виснет?

Добрый день всем!!!

Прошу помощи по вопросу оказания помощи раненым сталкерам чужеродной группировки например бандитам, военным и т. д. тем, кто в оригинале игры являются врагами ГГ.

Сделал следующее:

файл xr_wounded. script


Функция:
function action_wounded:execute ()
action_base.execute (self)
wound_manager = self.a.wound_manager

wound_manager_victim = xr_logic.pstor_retrieve(self.object, "wounded_victim")

local victim = nil
if wound_manager_victim == "actor" then
victim = db.actor
elseif tostring(wound_manager_victim) == "nil" then
victim = nil
else
local sim = alife()
if sim then
victim = sim:story_object(victim)
end
end


--if self.object:relation(db.actor) == game_object.enemy then
--self.object:disable_talk()
--else

self.object:enable_talk()
end
.....

закоментил эти строки!!!

Файл dialogs.scripts:

 

Функция:function transfer_medkit(first_speaker, second_speaker)
if first_speaker:object("medkit") ~= nil then
dialogs.relocate_item_section(second_speaker, "medkit", "out")
elseif first_speaker:object("medkit_army") ~= nil then
dialogs.relocate_item_section(second_speaker, "medkit_army", "out")
else
dialogs.relocate_item_section(second_speaker, "medkit_scientic", "out")
end

--' Тут надо анлочить аптечку для использования.
xr_wounded.unlock_medkit(second_speaker)

if second_speaker:relation(first_speaker) ~= game_object.enemy then
second_speaker:set_relation(game_object.friend, first_speaker)
end
first_speaker:change_character_reputation(10);
end
Изменил часть кода на:
if second_speaker:relation(first_speaker) == game_object.enemy then
second_speaker:set_relation(game_object.friend, first_speaker)
first_speaker:set_relation(game_object.friend, second_speaker)
end
first_speaker:change_character_reputation(10);
end

Кроме этого, добавил всем НПС в character_desc_simulation и другие файлы этого типа в их профиль диалоги по типу:
dm_help_wounded_medkit_dialog
hello_dialog
dm_hello_dialog

 

Однако, не смотря на то, что надпись на юзание появляется, при попытке этого действа следует вылет с аргументом: не может найти диалог "dm_hello_dialog". Как можно поправить сие???

Игра версии 1.0004, оригинал мод с использованием файлов АМК (amk.scripts и amk_mod.scripts).

Заранее СПАСИБО!!!

Изменено пользователем losiara
Как узнать/установить позицию курсора?

 

В оригинале есть в начале действо- когда ГГ показывают ПДА, посмотрел в коде- вроде как в движке всё мутится

Так и не понял как с курсором работать, мне хотя бы получение координат его нужно, и ещё желательно сделать в какой-то момент прозрачным, а потом снова вернуть ему картинку, это возможно?

 

 

не может найти диалог "dm_hello_dialog"

 

Автор: Моддер



Как лечить раненных НПС-врагов
Сложность: оч. легко
Совместимость с модами: легко совместимо
Многие люди в своих модификациях хотят добавить возможность лечить раненных врагов, как, например, в Солянке. Я тоже однажды заинтересовался этим вопросом и, не найдя на него ответа в интернете, занялся решением проблемы сам. В итоге мне это удалось и теперь выкладываю плоды своих стараний на просторы интернета :) .
Скрыть Инструкции

Запрет диалога с раненными противниками находится в файле xr_wounded.script, и выглядит так (я снабдил его комментариями, если вы не сильно шарите в скриптах):


if self.object:relation(db.actor) == game_object.enemy then --если отношение НПС к ГГ = отношению к врагум
self.object:disable_talk() --блокировать диалоги
else --иначе
self.object:enable_talk() --разрешить диалог
end --конец условия (if)
Дабы позволить ГГ говорить с врагами (только раненными) достаточно удалить лишнее и оставить всего одну строку:
self.object:enable_talk()
Но! Если ГГ попробует обратиться к раненным представителям бандитов, монолитовцев, наёмников, зомби (возможно), военных или противников на Арене - скорее всего произойдёт Фатал Еррор с логом на отсутствие подходящей фразы для диалога (в оригинальной игре с вероятностью 99%). Так вот, лично для себя я нашёл простое решение, которое подходило и по концепции моего мода - запретить диалог с данными группировками. Вот таким макаром:
local comm = self.object:character_community() --переменной обозначил "понятие" группировки обьекта (НПС)
if comm == "zombied" or --если НПС - зомби, или
comm == "bandit" or --НПС - бандит, или
comm == "monolith" or --НПС - монолитовец, или
comm == "arena_enemy" or --НПС - боец арены, или
comm == "killer" or --НПС - наёмник, или
comm == "military" then --НПС - вояка, тогда
self.object:disable_talk() --запретить диалог
else -- иначе
self.object:enable_talk() --разрешить диалог
end -- The End!
просто заменить изначальные строки этими и теперь ГГ сможет лечить врагов одиночек, долговцев, свободовцев и учёных.
Но есть ещё один момент. При лечении врагов, если всё сделать как было написано будет ещё одна проблемка - они так и останутся врагами после лечения и будут дальше атаковать ГГ.
Разумно было бы сделать НПС если не другом, то по крайней мере нейтралом. Для этого необходимо в файле dialogs.script кусок скрипта
if second_speaker:relation(first_speaker) ~= game_object.enemy then
second_speaker:set_relation(game_object.friend, first_speaker)
end
first_speaker:change_character_reputation(10);
end
заменить на
if second_speaker:relation(first_speaker) == game_object.enemy then
second_speaker:set_relation(game_object.friend, first_speaker)
first_speaker:set_relation(game_object.friend, second_speaker)
end
first_speaker:change_character_reputation(10);
end
Всё! ;)

 

Space.Marine

Я этот тутор видел, он не соот. запросу, там нельзя лечить врагов таких как бандит или военный... только раненых дружелюбных НПС (из оригинала).

Я уже решил проблему внимательнее покопавшись в инете, вот готовые скрипты:

----------------------------------------------------------------------------------------------------------------------


-- Схема раненного
-- автор: Диденко Руслан (Stohe)
-- TODO:
----------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------
--Evaluators
----------------------------------------------------------------------------------------------------------------------
class "evaluator_wound" (property_evaluator)
function evaluator_wound:__init(name, storage) super(nil, name)
self.a = storage
end
function evaluator_wound:evaluate ()
if self.a.wounded_set ~= true then return false end

--' self.a.wound_manager:update()
if self.mgr == nil then
self.mgr = self.object:motivation_action_manager()
end
if self.object:critically_wounded() == true then
return false
end
if self.mgr:evaluator(stalker_ids.property_enemy):evaluate() and
xr_logic.pstor_retrieve(self.object, "wounded_fight") == "true"
then
return false
end
return tostring(xr_logic.pstor_retrieve(self.object, "wounded_state")) ~= "nil"
end

class "evaluator_can_fight" (property_evaluator)
function evaluator_can_fight:__init(name, storage) super(nil, name)
self.a = storage
end
function evaluator_can_fight:evaluate ()
if self.object:critically_wounded() == true then
return true
end

return xr_logic.pstor_retrieve(self.object, "wounded_fight") ~= "false"
end

----------------------------------------------------------------------------------------------------------------------
--Actions
----------------------------------------------------------------------------------------------------------------------
class "action_wounded" (action_base)
function action_wounded:__init(name, storage) super(nil, name)
self.a = storage
end
function action_wounded:initialize ()
action_base.initialize (self)
self.object:set_desired_position()
self.object:set_desired_direction()
self.sound = "nil"


if self.a.help_start_dialog then
self.object:set_start_dialog(self.a.help_start_dialog)
end
self.object:wounded(true)
end
function action_wounded:execute ()
action_base.execute (self)
wound_manager = self.a.wound_manager

wound_manager_victim = xr_logic.pstor_retrieve(self.object, "wounded_victim")

local victim = nil
if wound_manager_victim == "actor" then
victim = db.actor
elseif tostring(wound_manager_victim) == "nil" then
victim = nil
else
local sim = alife()
if sim then
victim = sim:story_object(victim)
end
end

if self.object:character_community()~="monolith" and -- кроме монолита
self.object:character_community()~="zombied" then -- кроме зомбированных, они не лечатся и друзьями не становятся!!!
self.object:enable_talk()
else
self.object:disable_talk()
end

--[[ if self.object:relation(db.actor) == game_object.enemy then -- автор скрипта закоментил эту секцию.
self.object:disable_talk()
else
self.object:enable_talk()
end]]


wound_manager_state = xr_logic.pstor_retrieve(self.object, "wounded_state")
wound_manager_sound = xr_logic.pstor_retrieve(self.object, "wounded_sound")

local synsound = nil
if wound_manager_state == "true" then
local h = hit()
h.power = 0
h.direction = self.object:direction()
h.bone = "bip01_spine"
h.draftsman = db.actor
h.impulse = 0
h.type = hit.wound
self.object:hit(h)
else
-- является ли текущий звук синхронным для текущего стейта
for k,v in pairs(self.a.syndata) do
if v.state == wound_manager_state and
v.sound == wound_manager_sound
then
synsound = wound_manager_sound
end
end
--' жрание аптечек и прочей срани.
--' Использовать можно только если нам можно сейчас есть аптечку.
if self.a.use_medkit == true then
wound_manager:eat_medkit()
end

local emerg = nil
if wound_manager_state == "psy_shoot" then
emerg = {animation_nout = true}
end
state_mgr.set_state(self.object, wound_manager_state, nil, nil, {look_object = victim}, emerg, synsound)
end

if synsound == nil then
-- нужно отыграть фоновый
if self.sound ~= wound_manager_sound then
self.sound = wound_manager_sound
if self.sound == "nil" then
xr_sound.set_sound(self.object, nil)
else
xr_sound.set_sound(self.object, wound_manager_sound)
end
end
else
-- нужно зарубить фоновый
if self.sound ~= nil then
self.sound = "nil"
xr_sound.set_sound(self.object, nil)
end
end

local tt = db.storage[self.object:id()]
if tt.active_scheme and not self.object:is_talking() then
if db.actor then
if xr_logic.try_switch_to_another_section(self.object, tt[tt.active_scheme], db.actor) then
return
end
end
end
end
function action_wounded:finalize ()
action_base.finalize (self)
self.object:disable_talk()
xr_sound.set_sound(self.object, nil)
self.object:wounded(false)
end

----------------------------------------------------------------------------------------------------------------------
-- Class wound_manager
----------------------------------------------------------------------------------------------------------------------
class "Cwound_manager"
function Cwound_manager:__init(npc, storage)
self.npc = npc
self.a = storage
self.can_use_medkit = false
end
function Cwound_manager:update()
hp = 100*self.npc.health
psy = 100*self.npc.psy_health

-- printf("PSY [%s] HP [%s]", psy, hp)

self.state, self.sound = self:process_psy_wound(psy)

if self.state == "nil" and
self.sound == "nil"
then
-- проверяем на обычную раненость
self.fight = self:process_fight(hp)
self.victim = self:process_victim(hp)
self.state, self.sound = self:process_hp_wound(hp)
else
-- устанавливаем пси раненость
self.fight = "false"
self.cover = "false"
self.victim = "nil"
end
-- printf("f[%s]c[%s]v[%s]", utils.to_str(self.fight), utils.to_str(self.cover), utils.to_str(self.victim))
-- printf("st[%s]so[%s]", utils.to_str(self.state), utils.to_str(self.sound))

xr_logic.pstor_store(self.npc, "wounded_state", self.state)
xr_logic.pstor_store(self.npc, "wounded_sound", self.sound)
xr_logic.pstor_store(self.npc, "wounded_fight", self.fight)
xr_logic.pstor_store(self.npc, "wounded_victim", self.victim)
end
function Cwound_manager:unlock_medkit()
self.can_use_medkit = true
end
function Cwound_manager:eat_medkit()
if self.can_use_medkit == true then
if self.npc:object("medkit") ~= nil then
self.npc:eat(self.npc:object("medkit"))
elseif self.npc:object("medkit_army") ~= nil then
self.npc:eat(self.npc:object("medkit_army"))
elseif self.npc:object("medkit_scientic") ~= nil then
self.npc:eat(self.npc:object("medkit_scientic"))
end
end
self.can_use_medkit = false
self:hit_callback()
end
function Cwound_manager:process_fight(hp)
local key
key = self:get_key_from_distance(self.a.hp_fight, hp)
if key ~= nil then
if self.a.hp_fight[key].state then
return tostring(xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.hp_fight[key].state))
end
end
return "true"
end
function Cwound_manager:process_victim(hp)
local key
key = self:get_key_from_distance(self.a.hp_victim, hp)
if key ~= nil then
if self.a.hp_victim[key].state then
return tostring(xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.hp_victim[key].state))
end
end
return "nil"
end
function Cwound_manager:process_hp_wound(hp)
local key
key = self:get_key_from_distance(self.a.hp_state, hp)
if key ~= nil then
local r1,r2
if self.npc:see(db.actor) then
if self.a.hp_state_see[key].state then
r1 = xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.hp_state_see[key].state)
end
if self.a.hp_state_see[key].sound then
r2 = xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.hp_state_see[key].sound)
end
else
if self.a.hp_state[key].state then
r1 = xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.hp_state[key].state)
end
if self.a.hp_state[key].sound then
r2 = xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.hp_state[key].sound)
end
end
return tostring(r1),tostring(r2)
end
return "nil","nil"
end
function Cwound_manager:process_psy_wound(hp)
local key
key = self:get_key_from_distance(self.a.psy_state, hp)
if key ~= nil then
local r1,r2
if self.a.psy_state[key].state then
r1 = xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.psy_state[key].state)
end
if self.a.psy_state[key].sound then
r2 = xr_logic.pick_section_from_condlist(db.actor, self.npc, self.a.psy_state[key].sound)
end
return tostring(r1),tostring(r2)
end
return "nil","nil"
end
function Cwound_manager:get_key_from_distance(t, hp)
local key
for k,v in pairs(t) do
if v.dist >= hp then
key = k
else
return key
end
end
return key
end
function Cwound_manager:hit_callback()
if self.npc:alive() == false then
return
end

if self.npc:critically_wounded() == true then
return
end

self:update()
end

----------------------------------------------------------------------------------------------------------------------
-- binder
----------------------------------------------------------------------------------------------------------------------
function add_to_binder (object, ini, scheme, section, st)

local operators = {}
local properties = {}

properties["wounded"] = xr_evaluators_id.sidor_wounded_base
properties["can_fight"] = xr_evaluators_id.sidor_wounded_base + 1

operators["wounded"] = xr_actions_id.sidor_act_wounded_base + 0


local manager = object:motivation_action_manager ()
manager:add_evaluator (properties["wounded"], this.evaluator_wound("wounded", st))
manager:add_evaluator (properties["can_fight"], this.evaluator_can_fight("can_fight", st))

local action = this.action_wounded("wounded_action", st)
action:add_precondition (world_property(stalker_ids.property_alive, true))
action:add_precondition (world_property(properties["wounded"], true))
action:add_effect (world_property(properties["wounded"], false))
action:add_effect (world_property(stalker_ids.property_enemy, false))
action:add_effect (world_property(properties["can_fight"], true))
manager:add_action (operators["wounded"], action)

action = manager:action (xr_actions_id.alife)
action:add_precondition (world_property(properties["wounded"], false))

action = manager:action (stalker_ids.action_gather_items)
action:add_precondition (world_property(properties["wounded"], false))

action = manager:action (stalker_ids.action_combat_planner)
action:add_precondition (world_property(properties["can_fight"], true))

action = manager:action (stalker_ids.action_danger_planner)
action:add_precondition (world_property(properties["can_fight"], true))

action = manager:action (stalker_ids.action_anomaly_planner)
action:add_precondition (world_property(properties["can_fight"], true))

end


------------
-- Вызывается только в начале на чтении логики, создает экшены, эвалуаторы и производит
-- первичную настройку.
function set_wounded(npc, ini, scheme, section)
local st = xr_logic.assign_storage_and_bind(npc, ini, scheme, section)
st.wound_manager = Cwound_manager(npc, st)
end
-- Вызывается на переключении на новую секцию. Производит вычитывание настроек из текущей секции.
function reset_wounded(npc, scheme, st, section)
local wounded_section
if scheme == nil or scheme == "nil" then
wounded_section = utils.cfg_get_string(st.ini, st.section_logic, "wounded", npc, false, "")
else
wounded_section = utils.cfg_get_string(st.ini, section, "wounded", npc, false, "")
end
init_wounded(npc, st.ini, wounded_section, st.wounded, scheme)
st.wounded.wound_manager:hit_callback()
end
-- Функция чтения настроек. В нее передается секция, откуда их нужно читать.
local wounded_by_state = {
[0] = "wounded_heavy",
[1] = "wounded_heavy_2",
[2] = "wounded_heavy_3"
}

function init_wounded(npc, ini, section, st, scheme)
printf("WOUNDED SECTION [%s][%s]", tostring(section), tostring(scheme))

if tostring(section) == st.wounded_section and
tostring(section) ~= "nil"
then
return
end

st.wounded_section = utils.to_str(section)

local def = {}
local npc_community = npc:character_community()
if npc_community == "monolith" then
local state = wounded_by_state[math.mod(npc:id(), 3)]
def.hp_state = "10|"..state.."@nil"
def.hp_state_see = "10|"..state.."@nil"
def.psy_state = ""
def.hp_victim = "10|nil"
def.hp_cover = "10|false"
def.hp_fight = "10|false"
def.syndata = ""
def.help_dialog = nil
def.help_start_dialog = nil
def.use_medkit = false

elseif npc_community == "zombied" then
def.hp_state = "40|wounded_zombie@nil"
def.hp_state_see = "40|wounded_zombie@nil"
def.psy_state = ""
def.hp_victim = "40|nil"
def.hp_cover = "40|false"
def.hp_fight = "40|false"
def.syndata = ""
def.help_dialog = nil
def.help_start_dialog = nil
def.use_medkit = false

else
local state = wounded_by_state[math.mod(npc:id(), 3)]
def.hp_state = "10|"..state.."@help_heavy"
def.hp_state_see = "10|"..state.."@help_heavy"
def.psy_state = "50|{=best_pistol}psy_armed,psy_pain@wounded_psy|20|{=best_pistol}psy_shoot,psy_pain@{=best_pistol}wounded_psy_shoot,wounded_psy"
def.hp_victim = "10|nil"
def.hp_cover = "10|false"
def.hp_fight = "10|false"
def.syndata = ""
def.help_dialog = "dm_help_wounded_medkit_dialog"
def.help_start_dialog = nil
def.use_medkit = true
end


if tostring(section) == "nil" then
-- Загружаем дефолты!
st.hp_state = xr_meet.parse_data(npc, def.hp_state)
st.hp_state_see = xr_meet.parse_data(npc, def.hp_state_see)
st.psy_state = xr_meet.parse_data(npc, def.psy_state)
st.hp_victim = xr_meet.parse_data(npc, def.hp_victim)
st.hp_cover = xr_meet.parse_data(npc, def.hp_cover)
st.hp_fight = xr_meet.parse_data(npc, def.hp_fight)
st.syndata = xr_meet.parse_syn_data(npc, def.syndata)
st.help_dialog = def.help_dialog
st.help_start_dialog = nil
st.use_medkit = def.use_medkit
else
st.hp_state = xr_meet.parse_data(npc, utils.cfg_get_string(ini, section, "hp_state", npc, false, "", def.hp_state))
st.hp_state_see = xr_meet.parse_data(npc, utils.cfg_get_string(ini, section, "hp_state_see", npc, false, "", def.hp_state_see))
st.psy_state = xr_meet.parse_data(npc, utils.cfg_get_string(ini, section, "psy_state", npc, false, "", def.psy_state))
st.hp_victim = xr_meet.parse_data(npc, utils.cfg_get_string(ini, section, "hp_victim", npc, false, "", def.hp_victim))
st.hp_cover = xr_meet.parse_data(npc, utils.cfg_get_string(ini, section, "hp_cover", npc, false, "", def.hp_cover))
st.hp_fight = xr_meet.parse_data(npc, utils.cfg_get_string(ini, section, "hp_fight", npc, false, "", def.hp_fight))
st.syndata = xr_meet.parse_syn_data(npc, utils.cfg_get_string(ini, section, "syndata", npc, false, "", def.syndata))
st.help_dialog = utils.cfg_get_string(ini, section, "help_dialog", npc, false, "", def.help_dialog)
st.help_start_dialog = utils.cfg_get_string(ini, section, "help_start_dialog", npc, false, "", nil)
st.use_medkit = utils.cfg_get_bool(ini, section, "use_medkit", npc, false, def.use_medkit)
end

-- флажок, что функция хотя бы раз вызывалась
st.wounded_set = true
end

function unlock_medkit(npc)
if db.storage[npc:id()].wounded ~= nil then
db.storage[npc:id()].wounded.wound_manager:unlock_medkit()
end
end



function is_wounded(npc)
if db.storage[npc:id()].wounded ~= nil then
--' if npc:object("medkit") ~= nil and
--' db.storage[npc:id()].wounded.wound_manager.can_use_medkit == true
--' then
--' return false
--' end

return tostring(db.storage[npc:id()].wounded.wound_manager.state) ~= "nil"
end
return false
end

function hit_callback(npc_id)
if db.storage[npc_id].wounded ~= nil then
db.storage[npc_id].wounded.wound_manager:hit_callback()
end
end


function is_heavy_wounded_by_id(npc_id)
if db.storage[npc_id].wounded ~= nil then
return tostring(db.storage[npc_id].wounded.wound_manager.state) ~= "nil"
end
return false
end
function is_psy_wounded_by_id(npc_id)
if db.storage[npc_id].wounded ~= nil then
return db.storage[npc_id].wounded.wound_manager.state == "psy_pain" or
db.storage[npc_id].wounded.wound_manager.state == "psy_armed" or
db.storage[npc_id].wounded.wound_manager.state == "psy_shoot" or
db.storage[npc_id].wounded.wound_manager.state == "psycho_pain" or
db.storage[npc_id].wounded.wound_manager.state == "psycho_shoot"
end
return false
end
-- Помощь раненому
function help_wounded(npc) -- скрипт добавлен автором!!!
local snd
if npc:name()=="esc_vagon_wounded" or npc:name()=="val_escort_bandit_halfdead" then return end
snd = xr_sound.get_safe_sound_object("characters_voice\\human_01\\newbie\\help\\wounded_thanx\\thanx_"..math.random(1,3))
snd:play_no_feedback(npc, sound_object.s3d, 0, npc:position(), 1.0)

--amk.start_timer("healing_enemies",math_random(20,30),amk.pack_array_to_string( {npc:id(), npc:character_community()} ))
--amk.start_timer("healing_enemies",math_random(20,30), {npc:id(), npc:character_community()} )
npc:set_character_community("stalker", 0, 0)
npc:set_relation(game_object.friend, db.actor)
end

 

function allow_break_dialog(first_speaker, second_speaker, id)
if second_speaker:profile_name() == "osoznanie" then
return false
end

return true
end


function break_dialog(first_speaker, second_speaker, id)
first_speaker:stop_talk()
second_speaker:stop_talk()
end

function disable_talk_self(first_speaker, second_speaker)
first_speaker:disable_talk()
end
function disable_talk_victim(first_speaker, second_speaker)
second_speaker:disable_talk()
end

function punch(first_speaker, second_speaker)
--abort("KICK ASS !!!!")
--xr_punch.punch[first_speaker:id()] = second_speaker
db.storage[second_speaker:id()].punch.enabled = true
end

function get_money_then_leave(first_speaker, second_speaker)
db.storage[first_speaker:id()].meet.enabled = false
db.storage[first_speaker:id()].robber.enabled = true
end

function is_wounded(first_speaker, second_speaker)
if db.storage[first_speaker:id()].wounded ~= nil and
db.storage[first_speaker:id()].wounded.wound_manager.can_use_medkit == true
then
return false
end

return xr_wounded.is_wounded(first_speaker)
end
function is_opp_wounded(first_speaker, second_speaker, dialog_id)
if db.storage[second_speaker:id()].wounded ~= nil and
db.storage[second_speaker:id()].wounded.wound_manager.can_use_medkit == true
then
return false
end
return xr_wounded.is_wounded(second_speaker)
end
function is_not_wounded(first_speaker, second_speaker)
return not this.is_wounded(first_speaker, second_speaker)
end
function actor_have_medkit(first_speaker, second_speaker)
return first_speaker:object("medkit") ~= nil or
first_speaker:object("medkit_army") ~= nil or
first_speaker:object("medkit_scientic") ~= nil
end
function actor_have_bandage(first_speaker, second_speaker)
return first_speaker:object("bandage") ~= nil
end
function transfer_medkit(first_speaker, second_speaker)
if first_speaker:object("medkit") ~= nil then
dialogs.relocate_item_section(second_speaker, "medkit", "out")
elseif first_speaker:object("medkit_army") ~= nil then
dialogs.relocate_item_section(second_speaker, "medkit_army", "out")
else
dialogs.relocate_item_section(second_speaker, "medkit_scientic", "out")
end

--' Тут надо анлочить аптечку для использования.
xr_wounded.unlock_medkit(second_speaker)

if second_speaker:relation(first_speaker) ~= game_object.enemy then
second_speaker:set_relation(game_object.friend, first_speaker)
first_speaker:change_character_reputation(10)
else
first_speaker:change_character_reputation(-10)
xr_wounded.help_wounded(second_speaker)
end
end
function transfer_bandage(first_speaker, second_speaker)
dialogs.relocate_item_section(second_speaker, "bandage", "out")
second_speaker:set_relation(game_object.friend, first_speaker)
end
function kill_yourself(npc, actor)
npc:kill(actor)
end


--' Obsolete, do not use!!!
function relocate_item(victim, obj, type)
if db.actor and victim then
if type == "in" then
victim:transfer_item(obj, db.actor)
elseif type == "out" then
db.actor:transfer_item(obj, victim)
end
--'news_manager.relocate_item(db.actor, type, obj)
end
end
--' Use this function instead.
function relocate_item_section(victim, section, type)
if db.actor and victim then
if type == "in" then

--' Трансферить нужно только квестовые предметы.
if quest_section[section] == true and
victim:object(section) ~= nil
then
victim:transfer_item(victim:object(section), db.actor)
else
alife():create(section,
db.actor:position(),
db.actor:level_vertex_id(),
db.actor:game_vertex_id(),
db.actor:id())
end
elseif type == "out" then
db.actor:transfer_item(db.actor:object(section), victim)
end
news_manager.relocate_item(db.actor, type, section)
end
end


function relocate_money(victim, num, type)
if db.actor and victim then
if type == "in" then
db.actor:give_money(num)
game_stats.money_quest_update (num)
elseif type == "out" then
db.actor:transfer_money(num, victim)
game_stats.money_quest_update (-num)
end
news_manager.relocate_money(db.actor, type, num)
end
end

--'---------------------------------------------------------------------------------
--' DIALOG ALLOWED
--'---------------------------------------------------------------------------------
function dialog_allowed(object, victim, id)
if id ~= nil then
-- printf("*DIALOGS*: dialog_allowed: %s", id)
else
-- printf("*DIALOGS*: dialog_allowed: nil")
end
if db.storage[victim:id()].actor_dialogs ~= nil then
for k,v in pairs(db.storage[victim:id()].actor_dialogs) do
if v == id then return true end
end
end
return false
end
function dialog_not_disable(object, victim, id)
if id ~= nil then
-- printf("*DIALOGS*: dialog_disable:%s", id)
else
-- printf("*DIALOGS*: dialog_disable:nil")
end
if db.storage[victim:id()].actor_disable ~= nil then
for k,v in pairs(db.storage[victim:id()].actor_disable) do
if v == id then return false end
end
end
return true
end

function allow_wounded_dialog(object, victim, id)
if db.storage[victim:id()].wounded == nil then
return false
end
if db.storage[victim:id()].wounded.help_dialog == id then
return true
end
return false
end


-----------------------------------------------------------------------------------
-- LEVELS
-----------------------------------------------------------------------------------
function level_escape(first_speaker, second_speaker)
return level.name() == "l01_escape"
end

function level_garbage(first_speaker, second_speaker)
return level.name() == "l02_garbage"
end

function level_agroprom(first_speaker, second_speaker)
return level.name() == "l03_agroprom_ai2" or level.name() == "l03_agroprom"
end

-----------------------------------------------------------------------------------
-- Relation functions
-----------------------------------------------------------------------------------
function is_friend(first_speaker, second_speaker)
return first_speaker:relation(second_speaker) == game_object.friend
end

function is_not_friend(first_speaker, second_speaker)
return not is_friend(first_speaker, second_speaker)
end

function become_friend(first_speaker, second_speaker)
first_speaker:set_relation(game_object.friend, second_speaker)
end

-----------------------------------------------------------------------------------
-- Community
-----------------------------------------------------------------------------------
function actor_in_dolg(actor, npc)
if db.actor then
return db.actor:character_community() == "actor_dolg"
end
return false
end
function actor_not_in_dolg(actor, npc)
return not actor_in_dolg(actor, npc)
end
function actor_set_dolg(actor, npc)
printf("ACTOR NOW IN [DOLG] COMMUNITY")
if db.actor then
db.actor:set_character_community("actor_dolg", 0, 0)
end
return true
end
function actor_clear_community(actor, npc)
printf("ACTOR NOW IN [NEUTRAL] COMMUNITY")
if db.actor then
db.actor:set_character_community("actor", 0, 0)
end
return true
end

-----------------------------------------------------------------------------------
-- Money functions
-----------------------------------------------------------------------------------
function has_2000_money(first_speaker, second_speaker)
return first_speaker:money() >= 2000
end

-----------------------------------------------------------------------------------
-- TRADE
-----------------------------------------------------------------------------------
--' Инициализация торговли
function trade_init(seller, buyer)
db.storage[seller:id()].meet.begin_wait_to_see.begin = time_global()/1000
xr_position.setPosition(db.storage[seller:id()].meet.Seller,
db.storage[seller:id()].meet.Seller:level_vertex_id())
db.storage[seller:id()].meet.Buyer = buyer
end

function want_trade(seller, buyer)
if seller:relation(buyer) == game_object.friend or
seller:relation(buyer) == game_object.neutral
then
return true
else
return false
end
end

function dont_want_trade(seller, buyer)
return not want_trade(seller,buyer)
end

 

Возможно кому пригодится!!!

Изменено пользователем losiara

Как через скрипт привязать к актёру партиклы.

Но так что-бы они например включались через час, а потом

отключались.

@Stalker_Anom,

 

local p = particles_object("партикл")

p:play_at_pos...

 

Читай "справочник по функциям и классам".

 

включались через час, а потом отключались

Можно сделать через таймеры, например.

Добрый день. Такая проблема. Есть описанный класс дешифратора( на GUI-элементах)

 

 

class "Deshifrator" (CUIScriptWnd)

function Deshifrator:__init() super()
self:InitControls()
self:InitCallBacks()
end

function Deshifrator:__finalize()
end

function Deshifrator:InitControls()
local xml = CScriptXmlInit()
self:Init(0,0,1024,768)
xml:ParseFile("Deshifrator.xml")
self.frame1 = xml:InitFrame("frame1", self)
self.edit1 = xml:InitEditBox("frame1:edit1", self.frame1)
self:Register(xml:Init3tButton("frame1:button1", self.frame1), "button1")
self:Register(xml:Init3tButton("frame1:button2", self.frame1), "button2")
self.Static3 = xml:InitStatic("frame1:Static3", self.frame1)
self.Static4 = xml:InitStatic("frame1:Static4", self.frame1)
self.edit2 = xml:InitEditBox("frame1:edit2", self.frame1)
self.checkbox1 = xml:InitCheck("frame1:checkbox1", self.frame1)
self:Register(self.checkbox1, "checkbox1")
self.checkbox2 = xml:InitCheck("frame1:checkbox2", self.frame1)
self:Register(self.checkbox2, "checkbox2")

end

function Deshifrator:InitCallBacks()
self:AddCallback("edit1", ui_events.EDIT_TEXT_CHANGED, self.edit1_edit_text_changed, self)
self:AddCallback("button1", ui_events.BUTTON_CLICKED, self.button1_button_clicked, self)
self:AddCallback("button2", ui_events.BUTTON_CLICKED, self.button2_button_clicked, self)
self:AddCallback("checkbox1", ui_events.BUTTON_CLICKED, self.checkbox1_button_clicked, self)
self:AddCallback("checkbox2", ui_events.BUTTON_CLICKED, self.checkbox2_button_clicked, self)
end

function Deshifrator:edit1_GetText() --/получить введенный текст в edit1
return self.edit1:GetText()
end

function Deshifrator:edit1_edit_text_changed()

end

function Deshifrator:button1_button_clicked()

end

function Deshifrator:button2_button_clicked()

end

function Deshifrator:edit2_GetText() --/получить введенный текст в edit2
return self.edit2:GetText()
end

function Deshifrator:checkbox1_GetCheck() --/true/false - включен/отключен checkbox1
return self.checkbox1:GetCheck()
end

function Deshifrator:checkbox1_button_clicked()

end

function Deshifrator:checkbox2_GetCheck() --/true/false - включен/отключен checkbox2
return self.checkbox2:GetCheck()
end

function Deshifrator:checkbox2_button_clicked()

end

function Deshifrator:Hide()
self:GetHolder():start_stop_menu(self, true)
end

 

 

Но я не знаю, как правильно его активировать. Я пытаюсь через проверку на активация предмета сделать, сама проверка то работает, а интерфейс не вызываеться.

 

Делаю вот так, но как видно, не работает.

 

function actor_binder:repair_outfit_start(obj, who)
if obj then
if obj:section() == "deshifrator" then --здесь указываем предмет, при использовании которого будет срабатывать функция ниже
--episode_system.def_func() --здесь указываем ссылку на функцию. Сначала скрипт, в котором она написана, потом название самой функции
self.Deshifrator:Hide()
end
end
end

 

 

Класс зарегестрирован в class_registrator. Вызываеться ф-я repair_outfit_start(obj, who) через bind_stalker.

И вот лог ошибки:

 

[error]Arguments : LUA error: ...ow of chernobyl\gamedata\scripts\bind_stalker.script:455: attempt to index field 'Deshifrator' (a nil value)

 

 

Изменено пользователем CRAZY_STALKER666

@CRAZY_STALKER666, создай в своем скрипте функцию main() с таким кодом  


function main()
local hud = Deshifrator(get_hud())
level.start_stop_menu(hud, true)

end


и вызывай её.

Добрый день всем!!!

Нубский вопрос. Как телепортировать НПС в пределах локации, не ГГ, а именно НПС. Вызов будет происходить из логики НПС при получении хита по типу:

[hit]
on_info = %=функция телепортации...%
 

Вот прошерстил и не нашел ничего подобного в инете!!!

СПАСИБО!!!

На платформе ЗП:

xr_effects.script. Функция teleport_npc.

Изменено пользователем Jurok

@Sla-Sla, вызывал в точности, как у вас. Вылет:

 

[error]Arguments : LUA error: ...ow of chernobyl\gamedata\scripts\bind_stalker.script:455: attempt to index global 'Deshifrator' (a nil value)

 

@Sla-Sla, функцию вписал в deshifrator.script(там где и описание этого класса идет).

Вызывал как обычно, из bind_stalker

Вот вызов - Deshifrator.main()

Изменено пользователем CRAZY_STALKER666

Создайте аккаунт или авторизуйтесь, чтобы оставить комментарий

Комментарии могут оставлять только зарегистрированные пользователи

Создать аккаунт

Зарегистрировать новый аккаунт в нашем сообществе. Это несложно!

Зарегистрировать новый аккаунт

Войти

Есть аккаунт? Войти.

Войти
  • Недавно просматривали   0 пользователей

    • Ни один зарегистрированный пользователь не просматривает эту страницу.
×
×
  • Создать...