Вопросы по Lua скриптингу

Общая тема для вопросов по разработке скриптов на языке программирования Lua, в частности под MoonLoader.
  • Задавая вопрос, убедитесь, что его нет в списке частых вопросов и что на него ещё не отвечали (воспользуйтесь поиском).
  • Поищите ответ в теме посвященной разработке Lua скриптов в MoonLoader
  • Отвечая, убедитесь, что ваш ответ корректен.
  • Старайтесь как можно точнее выразить мысль, а если проблема связана с кодом, то обязательно прикрепите его к сообщению, используя блок [code=lua]здесь мог бы быть ваш код[/code].
  • Если вопрос связан с MoonLoader-ом первым делом желательно поискать решение на wiki.

Частые вопросы

Как научиться писать скрипты? С чего начать?
Информация - Гайд - Всё о Lua скриптинге для MoonLoader(https://blast.hk/threads/22707/)
Как вывести текст на русском? Вместо русского текста у меня какие-то каракули.
Изменить кодировку файла скрипта на Windows-1251. В Atom: комбинация клавиш Ctrl+Shift+U, в Notepad++: меню Кодировки -> Кодировки -> Кириллица -> Windows-1251.
Как получить транспорт, в котором сидит игрок?
Lua:
local veh = storeCarCharIsInNoSave(PLAYER_PED)
Как получить свой id или id другого игрока?
Lua:
local _, id = sampGetPlayerIdByCharHandle(PLAYER_PED) -- получить свой ид
local _, id = sampGetPlayerIdByCharHandle(ped) -- получить ид другого игрока. ped - это хендл персонажа
Как проверить, что строка содержит какой-то текст?
Lua:
if string.find(str, 'текст', 1, true) then
-- строка str содержит "текст"
end
Как эмулировать нажатие игровой клавиши?
Lua:
local game_keys = require 'game.keys' -- где-нибудь в начале скрипта вне функции main

setGameKeyState(game_keys.player.FIREWEAPON, -1) -- будет сэмулировано нажатие клавиши атаки
Все иды клавиш находятся в файле moonloader/lib/game/keys.lua.
Подробнее о функции setGameKeyState здесь: lua - setgamekeystate | BlastHack — DEV_WIKI(https://www.blast.hk/wiki/lua:setgamekeystate)
Как получить id другого игрока, в которого целюсь я?
Lua:
local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
  local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
  if result then -- проверить, прошло ли получение ида успешно
    -- здесь любые действия с полученным идом игрока
  end
end
Как зарегистрировать команду чата SAMP?
Lua:
-- До бесконечного цикла/задержки
sampRegisterChatCommand("mycommand", function (param)
     -- param будет содержать весь текст введенный после команды, чтобы разделить его на аргументы используйте string.match()
    sampAddChatMessage("MyCMD", -1)
end)
Крашит игру при вызове sampSendChat. Как это исправить?
Это происходит из-за бага в SAMPFUNCS, когда производится попытка отправки пакета определенными функциями изнутри события исходящих RPC и пакетов. Исправления для этого бага нет, но есть способ не провоцировать его. Вызов sampSendChat изнутри обработчика исходящих RPC/пакетов нужно обернуть в скриптовый поток с нулевой задержкой:
Lua:
function onSendRpc(id)
  -- крашит:
  -- sampSendChat('Send RPC: ' .. id)

  -- норм:
  lua_thread.create(function()
    wait(0)
    sampSendChat('Send RPC: ' .. id)
  end)
end
 
Последнее редактирование:

minxty

Известный
1,273
1,146
--[[ тут нужно установить задержку, так как скрипт может загрузиться раньше, чем скрипт, для которого нужно вводить команду ]]--
а еще легче, поставить z, y и прочие символы в начале имени, что бы скрипт самым последним загрузился
 

Corrygan

Известный
53
17
как юзать dl:AddConvexPolyFilled()

пытаюсь так, игру крашит без ошибок в мунлоге:
Lua:
function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

function RemoveFromChamsQuery(handle)
    ChamsQuery[handle] = nil
end

imgui.OnFrame(
    function() return true end,
    function(self)
        self.HideCursor = true
        if not isSampAvailable() then return end
        if not sampIsLocalPlayerSpawned() then return end
        local dl = imgui.GetBackgroundDrawList()
        local bones_pos = {}
        local bones = {
            head = 8,  -- голова
            neck = 6,  -- шея
            leftarm = 22, -- левая рука
            leftleg = 41, -- левая нога
            ass = 1,  -- таз
            rightleg = 51, -- правая нога
            rightarm = 32, -- правая рука
            returntoneck = 6,  -- вернуться к шее
        }
        for _, bone in pairs(bones) do
            local boneX, boneY, boneZ = getBodyPartCoordinates(bone, v)
            local bonesX, bonesY = convert3DCoordsToScreen(boneX, boneY, boneZ)
            if bonesX and bonesY then
                table.insert(bones_pos, imgui.ImVec2(bonesX, bonesY))
            end
        end
        if settings.chams then
            for handle, color in pairs(ChamsQuery) do
                dl:AddConvexPolyFilled(bones_pos[1], bones_pos[2], bones_pos[3], bones_pos[4], bones_pos[5], bones_pos[6], bones_pos[7], #bones_pos color, true)
            end
        end
    end
)

--main

whil true do
    wait(0)
   
    if elements.chams[0] then
        for k,v in ipairs(getAllChars()) do
            if v ~= PLAYER_PED then
                if ChamsQuery[v] then
                    if not isCharOnScreen(v) then          
                        RemoveFromChamsQuery(v)
                    end
                elseif isCharOnScreen(v) then
                    local _, id = sampGetPlayerIdByCharHandle(v)
                    AddPlayerToChamsQuery(v, sampGetPlayerColor(id))
                end
            end
        end
    end
 

dmitry.karle

Известный
408
109
как юзать dl:AddConvexPolyFilled()

пытаюсь так, игру крашит без ошибок в мунлоге:
Lua:
function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

function RemoveFromChamsQuery(handle)
    ChamsQuery[handle] = nil
end

imgui.OnFrame(
    function() return true end,
    function(self)
        self.HideCursor = true
        if not isSampAvailable() then return end
        if not sampIsLocalPlayerSpawned() then return end
        local dl = imgui.GetBackgroundDrawList()
        local bones_pos = {}
        local bones = {
            head = 8,  -- голова
            neck = 6,  -- шея
            leftarm = 22, -- левая рука
            leftleg = 41, -- левая нога
            ass = 1,  -- таз
            rightleg = 51, -- правая нога
            rightarm = 32, -- правая рука
            returntoneck = 6,  -- вернуться к шее
        }
        for _, bone in pairs(bones) do
            local boneX, boneY, boneZ = getBodyPartCoordinates(bone, v)
            local bonesX, bonesY = convert3DCoordsToScreen(boneX, boneY, boneZ)
            if bonesX and bonesY then
                table.insert(bones_pos, imgui.ImVec2(bonesX, bonesY))
            end
        end
        if settings.chams then
            for handle, color in pairs(ChamsQuery) do
                dl:AddConvexPolyFilled(bones_pos[1], bones_pos[2], bones_pos[3], bones_pos[4], bones_pos[5], bones_pos[6], bones_pos[7], #bones_pos color, true)
            end
        end
    end
)

--main

whil true do
    wait(0)
  
    if elements.chams[0] then
        for k,v in ipairs(getAllChars()) do
            if v ~= PLAYER_PED then
                if ChamsQuery[v] then
                    if not isCharOnScreen(v) then         
                        RemoveFromChamsQuery(v)
                    end
                elseif isCharOnScreen(v) then
                    local _, id = sampGetPlayerIdByCharHandle(v)
                    AddPlayerToChamsQuery(v, sampGetPlayerColor(id))
                end
            end
        end
    end
Lua:
imgui.OnFrame(
    function() return true end,
    function(self)
        self.HideCursor = true
        if not isSampAvailable() or not sampIsLocalPlayerSpawned() then return end
        local dl = imgui.GetBackgroundDrawList()
        local bones_pos = {}
        local bones = {
            head = 8,     -- голова
            neck = 6,     -- шея
            leftarm = 22, -- левая рука
            leftleg = 41, -- левая нога
            ass = 1,      -- таз
            rightleg = 51,-- правая нога
            rightarm = 32,-- правая рука
            returntoneck = 6, -- замыкаем контур на шею
        }
        for _, bone in pairs(bones) do
            local boneX, boneY, boneZ = getBodyPartCoordinates(bone, v)
            if boneX and boneY and boneZ then
                local scrX, scrY = convert3DCoordsToScreen(boneX, boneY, boneZ)
                if scrX and scrY then
                    table.insert(bones_pos, imgui.ImVec2(scrX, scrY))
                end
            end
        end
        if settings.chams and #bones_pos >= 3 then
            for handle, color in pairs(ChamsQuery) do
                dl:AddConvexPolyFilled(bones_pos, #bones_pos, color, true)
            end
        end
    end
)

check
 

Corrygan

Известный
53
17
как в мимгуи проверить инпут на наличие в нем текста?
if #nick_buffer[0] ~= 0 then - не работает
if nick_buffer[0]:len() ~= 0 then - не работает
if nick_buffer[0] ~= "" then - не работает
сразу крашит без ошибки в мунлоге, фулл код:

Lua:
local nick_buffer = imgui.new.char[128]()

--OnFrame
imgui.PushItemWidth(100)
imgui.InputText("##nick_buffer_for_exceptions_add", nick_buffer, 128)
imgui.PopItemWidth()

if nick_buffer[0] ~= "" then --?????
    nick_buffer[0] = nick_buffer[0]:gsub("%%", "")
    imgui.SameLine()
    if imgui.Button(nick_buffer[0], imgui.ImVec2(imgui.CalcTextSize(nick_buffer[0]).x + 20, 20)) then
        tryInsert(ignored_nicks, nick_buffer[0])
    end

    local nick_lower = nick_buffer[0]:lower()
    for id = 0, sampGetMaxPlayerId(false) do
        if sampIsPlayerConnected(id) then
            local nick = sampGetPlayerNickname(id)
            if nick:lower():find(nick_lower) then
                imgui.SameLine()
                local button_string = nick.."["..id.."]"
                if imgui.Button(button_string, imgui.ImVec2(imgui.CalcTextSize(button_string).x + 20, 20)) then
                    tryInsert(ignored_nicks, nick)
                end
                break
            end
        end
    end
end
комментировал код частями, оставлял только if nick_buffer[0] с разными вариантами проверок и end, крашило, а когда комментил норм было

Lua:
imgui.OnFrame(
    function() return true end,
    function(self)
        self.HideCursor = true
        if not isSampAvailable() or not sampIsLocalPlayerSpawned() then return end
        local dl = imgui.GetBackgroundDrawList()
        local bones_pos = {}
        local bones = {
            head = 8,     -- голова
            neck = 6,     -- шея
            leftarm = 22, -- левая рука
            leftleg = 41, -- левая нога
            ass = 1,      -- таз
            rightleg = 51,-- правая нога
            rightarm = 32,-- правая рука
            returntoneck = 6, -- замыкаем контур на шею
        }
        for _, bone in pairs(bones) do
            local boneX, boneY, boneZ = getBodyPartCoordinates(bone, v)
            if boneX and boneY and boneZ then
                local scrX, scrY = convert3DCoordsToScreen(boneX, boneY, boneZ)
                if scrX and scrY then
                    table.insert(bones_pos, imgui.ImVec2(scrX, scrY))
                end
            end
        end
        if settings.chams and #bones_pos >= 3 then
            for handle, color in pairs(ChamsQuery) do
                dl:AddConvexPolyFilled(bones_pos, #bones_pos, color, true)
            end
        end
    end
)

check
тоже не сработало
 
Последнее редактирование:

dmitry.karle

Известный
408
109
как в мимгуи проверить инпут на наличие в нем текста?
if #nick_buffer[0] ~= 0 then - не работает
if nick_buffer[0]:len() ~= 0 then - не работает
if nick_buffer[0] ~= "" then - не работает
сразу крашит без ошибки в мунлоге, фулл код:

Lua:
local nick_buffer = imgui.new.char[128]()

--OnFrame
imgui.PushItemWidth(100)
imgui.InputText("##nick_buffer_for_exceptions_add", nick_buffer, 128)
imgui.PopItemWidth()

if nick_buffer[0] ~= "" then --?????
    nick_buffer[0] = nick_buffer[0]:gsub("%%", "")
    imgui.SameLine()
    if imgui.Button(nick_buffer[0], imgui.ImVec2(imgui.CalcTextSize(nick_buffer[0]).x + 20, 20)) then
        tryInsert(ignored_nicks, nick_buffer[0])
    end

    local nick_lower = nick_buffer[0]:lower()
    for id = 0, sampGetMaxPlayerId(false) do
        if sampIsPlayerConnected(id) then
            local nick = sampGetPlayerNickname(id)
            if nick:lower():find(nick_lower) then
                imgui.SameLine()
                local button_string = nick.."["..id.."]"
                if imgui.Button(button_string, imgui.ImVec2(imgui.CalcTextSize(button_string).x + 20, 20)) then
                    tryInsert(ignored_nicks, nick)
                end
                break
            end
        end
    end
end
комментировал код частями, оставлял только if nick_buffer[0] с разными вариантами проверок и end, крашило, а когда комментил норм было


тоже не сработало
Lua:
if imgui.InputTextWithHint('##radio', fa.MAGNIFYING_GLASS..u8' Поиск объявлений/эфиров ', radio, ffi.sizeof(radio)) then
    local text = u8:decode(ffi.string(radio))
    if text ~= "" then
        sampAddChatMessage(text, -1)
    else
        sampAddChatMessage("Вы не ввели текст для поиска", -1)
    end
end
под свой код переделай (мой для примера)
а там что за ошибка? так-же краш?
 

Corrygan

Известный
53
17
Lua:
if imgui.InputTextWithHint('##radio', fa.MAGNIFYING_GLASS..u8' Поиск объявлений/эфиров ', radio, ffi.sizeof(radio)) then
    local text = u8:decode(ffi.string(radio))
    if text ~= "" then
        sampAddChatMessage(text, -1)
    else
        sampAddChatMessage("Вы не ввели текст для поиска", -1)
    end
end
под свой код переделай (мой для примера)
а там что за ошибка? так-же краш?
да, просто краш
ошибки в мунлоге нет
 

dmitry.karle

Известный
408
109
да, просто краш
ошибки в мунлоге нет
Lua:
function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

function RemoveFromChamsQuery(handle)
    ChamsQuery[handle] = nil
end

imgui.OnFrame(
    function() return true end,
    function(self)
        self.HideCursor = true
        if not isSampAvailable() then return end
        if not sampIsLocalPlayerSpawned() then return end
       
        if not settings.chams then return end
       
        local dl = imgui.GetBackgroundDrawList()
       
        for handle, color in pairs(ChamsQuery) do
            if not isCharOnScreen(handle) then
                RemoveFromChamsQuery(handle)
            else
                local bones_pos = {}
                
local bones = {
            head = 8,     -- голова
            neck = 6,     -- шея
            leftarm = 22, -- левая рука
            leftleg = 41, -- левая нога
            ass = 1,      -- таз
            rightleg = 51,-- правая нога
            rightarm = 32,-- правая рука
            returntoneck = 6, -- замыкаем контур на шею
        }
               
                for _, bone in pairs(bones) do
                    local boneX, boneY, boneZ = getBodyPartCoordinates(bone, handle)
                    if boneX then
                        local bonesX, bonesY = convert3DCoordsToScreen(boneX, boneY, boneZ)
                        if bonesX and bonesY then
                            table.insert(bones_pos, imgui.ImVec2(bonesX, bonesY))
                        end
                    end
                end
               
                if #bones_pos >= 3 then
                    dl:AddConvexPolyFilled(bones_pos, #bones_pos, color, true)
                end
            end
        end
    end
)

function main()
    ChamsQuery = {}
   
    repeat wait(0) until isSampAvailable()
   
    while true do
        wait(0)
       
        if elements.chams[0] then
            for k,v in ipairs(getAllChars()) do
                if v ~= PLAYER_PED then
                    if ChamsQuery[v] then
                        if not isCharOnScreen(v) then        
                            RemoveFromChamsQuery(v)
                        end
                    elseif isCharOnScreen(v) then
                        local _, id = sampGetPlayerIdByCharHandle(v)
                        if id ~= nil then
                            AddPlayerToChamsQuery(v, sampGetPlayerColor(id))
                        end
                    end
                end
            end
        end
    end
end
попробуй
 

Corrygan

Известный
53
17
Lua:
function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

function RemoveFromChamsQuery(handle)
    ChamsQuery[handle] = nil
end

imgui.OnFrame(
    function() return true end,
    function(self)
        self.HideCursor = true
        if not isSampAvailable() then return end
        if not sampIsLocalPlayerSpawned() then return end
      
        if not settings.chams then return end
      
        local dl = imgui.GetBackgroundDrawList()
      
        for handle, color in pairs(ChamsQuery) do
            if not isCharOnScreen(handle) then
                RemoveFromChamsQuery(handle)
            else
                local bones_pos = {}
               
local bones = {
            head = 8,     -- голова
            neck = 6,     -- шея
            leftarm = 22, -- левая рука
            leftleg = 41, -- левая нога
            ass = 1,      -- таз
            rightleg = 51,-- правая нога
            rightarm = 32,-- правая рука
            returntoneck = 6, -- замыкаем контур на шею
        }
              
                for _, bone in pairs(bones) do
                    local boneX, boneY, boneZ = getBodyPartCoordinates(bone, handle)
                    if boneX then
                        local bonesX, bonesY = convert3DCoordsToScreen(boneX, boneY, boneZ)
                        if bonesX and bonesY then
                            table.insert(bones_pos, imgui.ImVec2(bonesX, bonesY))
                        end
                    end
                end
              
                if #bones_pos >= 3 then
                    dl:AddConvexPolyFilled(bones_pos, #bones_pos, color, true)
                end
            end
        end
    end
)

function main()
    ChamsQuery = {}
  
    repeat wait(0) until isSampAvailable()
  
    while true do
        wait(0)
      
        if elements.chams[0] then
            for k,v in ipairs(getAllChars()) do
                if v ~= PLAYER_PED then
                    if ChamsQuery[v] then
                        if not isCharOnScreen(v) then       
                            RemoveFromChamsQuery(v)
                        end
                    elseif isCharOnScreen(v) then
                        local _, id = sampGetPlayerIdByCharHandle(v)
                        if id ~= nil then
                            AddPlayerToChamsQuery(v, sampGetPlayerColor(id))
                        end
                    end
                end
            end
        end
    end
end
попробуй
без изменений 🥲

я уже с этим смирился, подскажи лучше, как это пофиксить?
почему-то не удаляется любой элемент, можно удалить только первый по нажатию кнопочки в попапе, а потом можно следующий, т.к. он первым стал
Lua:
local settings = {
    ignored = {},
    --тут еще всякое
}

local elements = {
    ignored = settings.ignored,
    --тут тот же всякое
}

--imgui
    if imgui.Button(u8"Список исключений", imgui.ImVec2(160, 26)) then
    imgui.OpenPopup("##list_of_exceptions")
end

imgui.SetNextWindowSize(imgui.ImVec2(300, 470), imgui.Cond.FirstUseEver)
if imgui.BeginPopupModal("##list_of_exceptions", false, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoMove) then

    imgui.Separator()

    for k, v in pairs(elements.ignored) do
        imgui.SetWindowFontScale(1.4)
        imgui.Text(k .. ".")
        imgui.SameLine()
        imgui.CenterText(v)
        imgui.SameLine()
        imgui.SetWindowFontScale(1.0)

        imgui.SetCursorPosX(300 - 25)
        if imgui.Button("X", imgui.ImVec2(19, 19)) then -- сюда жму
            table.remove(settings.ignored, k)
            save()
        end
        imgui.Separator()
    end

    imgui.SetCursorPos(imgui.ImVec2(115, 440))
    if imgui.Button(u8"Закрыть", imgui.ImVec2(70, 25)) then
        imgui.CloseCurrentPopup()
    end
    imgui.EndPopup()
end
 
Последнее редактирование:

Masayuki

Участник
94
36
без изменений 🥲

я уже с этим смирился, подскажи лучше, как это пофиксить?
почему-то не удаляется любой элемент, можно удалить только первый по нажатию кнопочки в попапе, а потом можно следующий, т.к. он первым стал
Lua:
local settings = {
    ignored = {},
    --тут еще всякое
}

local elements = {
    ignored = settings.ignored,
    --тут тот же всякое
}

--imgui
    if imgui.Button(u8"Список исключений", imgui.ImVec2(160, 26)) then
    imgui.OpenPopup("##list_of_exceptions")
end

imgui.SetNextWindowSize(imgui.ImVec2(300, 470), imgui.Cond.FirstUseEver)
if imgui.BeginPopupModal("##list_of_exceptions", false, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoMove) then

    imgui.Separator()

    for k, v in pairs(elements.ignored) do
        imgui.SetWindowFontScale(1.4)
        imgui.Text(k .. ".")
        imgui.SameLine()
        imgui.CenterText(v)
        imgui.SameLine()
        imgui.SetWindowFontScale(1.0)

        imgui.SetCursorPosX(300 - 25)
        if imgui.Button("X", imgui.ImVec2(19, 19)) then -- сюда жму
            table.remove(settings.ignored, k)
            save()
        end
        imgui.Separator()
    end

    imgui.SetCursorPos(imgui.ImVec2(115, 440))
    if imgui.Button(u8"Закрыть", imgui.ImVec2(70, 25)) then
        imgui.CloseCurrentPopup()
    end
    imgui.EndPopup()
end
imgui.Button('X##'..k, imgui.ImVec2(19, 19))
 
  • Нравится
Реакции: Corrygan

Corrygan

Известный
53
17
в чем ошибка?
Lua:
for _, ped in ipairs(getAllChars()) do
    if ped ~= PLAYER_PED and isCharOnScreen(ped) then
    local result, id = sampGetPlayerIdByCharHandle(ped)
        if result then
            for _, bone in ipairs(temp_bones) do
                local peds_bone = getBodyPartCoordinates(bone, ped)
                local bone_2d = vector2d(convert3DCoordsToScreen(peds_bone:get())) --589 строка
                local dist_sight = getDistanceBetweenCoords2d(bone_2d.x, bone_2d.y, sight_2d.x, sight_2d.y)
                local dist = getDistanceBetweenCoords3d(sight_3d.x, sight_3d.y, sight_3d.z, peds_bone:get())
                if dist_sight < tdist and dist < weapon.dist and (not legit or legit.dist_sight > dist_sight) and not isCharDead(ped) and not sampIsPlayerPaused(id) and isLineOfSightClear(sight_3d.x, sight_3d.y, sight_3d.z, peds_bone.x, peds_bone.y, peds_bone.z, true, not settings.ignoreveh, false, true, false) then
                    legit = {
                        dist = dist,
                        dist_sight = dist_sight,
                        bone_num = bone,
                        bone = peds_bone,
                        ped = ped,
                        id = id
                    }
                    break
                end
            end
        end
    end
    ::next::
end
[02:42:00.033757] (error) script: D:\Games\GTA San Andreas\moonloader\script.lua:589: attempt to index local 'peds_bone' (a number value)
stack traceback:
D:\Games\GTA San Andreas\moonloader\script.lua: in function <D:\Games\GTA San Andreas\moonloader\script.lua:489>
[02:42:00.033757] (error) script: Script died due to an error. (194A0DEC)
 
Последнее редактирование:

dmitry.karle

Известный
408
109
в чем ошибка?
Lua:
for _, ped in ipairs(getAllChars()) do
    if ped ~= PLAYER_PED and isCharOnScreen(ped) then
    local result, id = sampGetPlayerIdByCharHandle(ped)
        if result then
            for _, bone in ipairs(temp_bones) do
                local peds_bone = getBodyPartCoordinates(bone, ped)
                local bone_2d = vector2d(convert3DCoordsToScreen(peds_bone:get())) --589 строка
                local dist_sight = getDistanceBetweenCoords2d(bone_2d.x, bone_2d.y, sight_2d.x, sight_2d.y)
                local dist = getDistanceBetweenCoords3d(sight_3d.x, sight_3d.y, sight_3d.z, peds_bone:get())
                if dist_sight < tdist and dist < weapon.dist and (not legit or legit.dist_sight > dist_sight) and not isCharDead(ped) and not sampIsPlayerPaused(id) and isLineOfSightClear(sight_3d.x, sight_3d.y, sight_3d.z, peds_bone.x, peds_bone.y, peds_bone.z, true, not settings.ignoreveh, false, true, false) then
                    legit = {
                        dist = dist,
                        dist_sight = dist_sight,
                        bone_num = bone,
                        bone = peds_bone,
                        ped = ped,
                        id = id
                    }
                    break
                end
            end
        end
    end
    ::next::
end
 

Corrygan

Известный
53
17
1) что делает эта функция?
нигде не могу найти информации про sampStorePlayerAimData
Lua:
function getCamMode()
   local aimptr = allocateMemory(31)
   local _, pid = sampGetPlayerIdByCharHandle(PLAYER_PED)
   sampStorePlayerAimData(pid, aimptr)
   local cam_mode = memory.getuint8(aimptr, 0)
   freeMemory(aimptr)
   return cam_mode
end

2) ивент происходит когда я слежу или за мной?
Lua:
INCOMING_RPCS[RPC.PLAYERSPECTATEPLAYER]       = {'onSpectatePlayer', {playerId = 'int16'}, {camType = 'int8'}}

3) аналогично с пакетом
Lua:
OUTCOMING_PACKETS[PACKET.SPECTATOR_SYNC]      = {'onSendSpectatorSync', function(bs) return utils.process_outcoming_sync_data(bs, 'SpectatorSyncData') end, empty_writer}
 
Последнее редактирование: