Вопросы по 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
 
Последнее редактирование:

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,771
11,214
Как тему подключить?
название функции в OnInitialize, например
Lua:
imgui.OnInitialize(function()
    imgui.SpotifyTheme()
end)

function imgui.SpotifyTheme()
    -- 121212 - 0.07, 0.07, 0.07

    
    imgui.SwitchContext()
    --==[ STYLE ]==--
    imgui.GetStyle().WindowPadding = imgui.ImVec2(5, 5)
    imgui.GetStyle().FramePadding = imgui.ImVec2(5, 5)
    imgui.GetStyle().ItemSpacing = imgui.ImVec2(5, 5)
    imgui.GetStyle().ItemInnerSpacing = imgui.ImVec2(4, 4)
    imgui.GetStyle().TouchExtraPadding = imgui.ImVec2(5, 5)
    imgui.GetStyle().IndentSpacing = 5
    imgui.GetStyle().ScrollbarSize = 10
    imgui.GetStyle().GrabMinSize = 10

    --==[ BORDER ]==--
    imgui.GetStyle().WindowBorderSize = 0
    imgui.GetStyle().ChildBorderSize = 1
    imgui.GetStyle().PopupBorderSize = 0
    imgui.GetStyle().FrameBorderSize = 0
    imgui.GetStyle().TabBorderSize = 0

    --==[ ROUNDING ]==--
    imgui.GetStyle().WindowRounding = 5
    imgui.GetStyle().ChildRounding = 5
    imgui.GetStyle().FrameRounding = 5
    imgui.GetStyle().PopupRounding = 5
    imgui.GetStyle().ScrollbarRounding = 5
    imgui.GetStyle().GrabRounding = 5
    imgui.GetStyle().TabRounding = 5

    --==[ ALIGN ]==--
    imgui.GetStyle().WindowTitleAlign = imgui.ImVec2(0.5, 0.5)
    imgui.GetStyle().ButtonTextAlign = imgui.ImVec2(0.5, 0.5)
    imgui.GetStyle().SelectableTextAlign = imgui.ImVec2(0.5, 0.5)

    --==[ COLORS ]==--
    imgui.GetStyle().Colors[imgui.Col.Text]                   = imgui.ImVec4(1.00, 1.00, 1.00, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TextDisabled]           = imgui.ImVec4(0.50, 0.50, 0.50, 1.00)
    imgui.GetStyle().Colors[imgui.Col.WindowBg]               = imgui.ImVec4(0.07, 0.07, 0.07, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ChildBg]                = imgui.ImVec4(0.09, 0.09, 0.09, 1.00)
    imgui.GetStyle().Colors[imgui.Col.PopupBg]                = imgui.ImVec4(0.09, 0.09, 0.09, 1.00)
    imgui.GetStyle().Colors[imgui.Col.Border]                 = imgui.ImVec4(0, 0, 0, 0.5)
    imgui.GetStyle().Colors[imgui.Col.BorderShadow]           = imgui.ImVec4(0.00, 0.00, 0.00, 1.00)
    imgui.GetStyle().Colors[imgui.Col.FrameBg]                = imgui.ImVec4(0.12, 0.12, 0.12, 1.00)
    imgui.GetStyle().Colors[imgui.Col.FrameBgHovered]         = imgui.ImVec4(0.25, 0.25, 0.26, 1.00)
    imgui.GetStyle().Colors[imgui.Col.FrameBgActive]          = imgui.ImVec4(0.25, 0.25, 0.26, 1.00)

    imgui.GetStyle().Colors[imgui.Col.TitleBg]                = imgui.ImVec4(0.07, 0.07, 0.07, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TitleBgActive]          = imgui.ImVec4(0.07, 0.07, 0.07, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TitleBgCollapsed]       = imgui.ImVec4(0.07, 0.07, 0.07, 1.00)

    imgui.GetStyle().Colors[imgui.Col.MenuBarBg]              = imgui.ImVec4(0.12, 0.12, 0.12, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarBg]            = imgui.ImVec4(0.12, 0.12, 0.12, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarGrab]          = imgui.ImVec4(0.00, 0.00, 0.00, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarGrabHovered]   = imgui.ImVec4(0.41, 0.41, 0.41, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarGrabActive]    = imgui.ImVec4(0.51, 0.51, 0.51, 1.00)
    
    imgui.GetStyle().Colors[imgui.Col.CheckMark]              = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)
    imgui.GetStyle().Colors[imgui.Col.SliderGrab]             = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)
    imgui.GetStyle().Colors[imgui.Col.SliderGrabActive]       = imgui.ImVec4(0.12, 0.84, 0.38, 1.00)

    imgui.GetStyle().Colors[imgui.Col.Button]                 = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ButtonHovered]          = imgui.ImVec4(0.12, 0.84, 0.38, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ButtonActive]           = imgui.ImVec4(0.12, 0.84, 0.38, 1.00)

    imgui.GetStyle().Colors[imgui.Col.Header]                 = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)
    imgui.GetStyle().Colors[imgui.Col.HeaderHovered]          = imgui.ImVec4(0.12, 0.84, 0.38, 1.00)
    imgui.GetStyle().Colors[imgui.Col.HeaderActive]           = imgui.ImVec4(0.12, 0.84, 0.38, 1.00)

    imgui.GetStyle().Colors[imgui.Col.Separator]              = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)
    imgui.GetStyle().Colors[imgui.Col.SeparatorHovered]       = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)
    imgui.GetStyle().Colors[imgui.Col.SeparatorActive]        = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)

    imgui.GetStyle().Colors[imgui.Col.ResizeGrip]             = imgui.ImVec4(0.11, 0.73, 0.33, 0.25)
    imgui.GetStyle().Colors[imgui.Col.ResizeGripHovered]      = imgui.ImVec4(0.12, 0.84, 0.38, 0.67)
    imgui.GetStyle().Colors[imgui.Col.ResizeGripActive]       = imgui.ImVec4(0.12, 0.84, 0.38, 0.95)

    imgui.GetStyle().Colors[imgui.Col.Tab]                    = imgui.ImVec4(0.11, 0.73, 0.33, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TabHovered]             = imgui.ImVec4(0.12, 0.84, 0.38, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TabActive]              = imgui.ImVec4(0.12, 0.84, 0.38, 1.00)

    imgui.GetStyle().Colors[imgui.Col.TabUnfocused]           = imgui.ImVec4(0.07, 0.10, 0.15, 0.97)
    imgui.GetStyle().Colors[imgui.Col.TabUnfocusedActive]     = imgui.ImVec4(0.14, 0.26, 0.42, 1.00)
    imgui.GetStyle().Colors[imgui.Col.PlotLines]              = imgui.ImVec4(0.61, 0.61, 0.61, 1.00)
    imgui.GetStyle().Colors[imgui.Col.PlotLinesHovered]       = imgui.ImVec4(1.00, 0.43, 0.35, 1.00)
    imgui.GetStyle().Colors[imgui.Col.PlotHistogram]          = imgui.ImVec4(0.90, 0.70, 0.00, 1.00)
    imgui.GetStyle().Colors[imgui.Col.PlotHistogramHovered]   = imgui.ImVec4(1.00, 0.60, 0.00, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TextSelectedBg]         = imgui.ImVec4(1.00, 0.00, 0.00, 0.35)
    imgui.GetStyle().Colors[imgui.Col.DragDropTarget]         = imgui.ImVec4(1.00, 1.00, 0.00, 0.90)
    imgui.GetStyle().Colors[imgui.Col.NavHighlight]           = imgui.ImVec4(0.26, 0.59, 0.98, 1.00)
    imgui.GetStyle().Colors[imgui.Col.NavWindowingHighlight]  = imgui.ImVec4(1.00, 1.00, 1.00, 0.70)
    imgui.GetStyle().Colors[imgui.Col.NavWindowingDimBg]      = imgui.ImVec4(0.80, 0.80, 0.80, 0.20)
    imgui.GetStyle().Colors[imgui.Col.ModalWindowDimBg]       = imgui.ImVec4(0.00, 0.00, 0.00, 0.70)
end
 

dendy.

Активный
351
66
ну так скинь лог если скрипт крашит

1650399453834.png
Крашит когда нажимаю любую кнопку

Делал по вот етому https://www.blast.hk/threads/13380/...ользования,-Последнее редактирование: Четверг
 
Последнее редактирование:

shrug228

Активный
212
75
Ох сколько от меня вопросов будет по imgui сегодня... Есть input и кнопка рядом с ним (в той же строке), нужно сразу при появлении инпута сделать его в фокусе. Ну я хоть и дурак, но не прям конченный. Покопался и нашел функцию imgui.SetKeyboardFocusHere(). Вроде все зашибись, но фокус забирает с себя какую-либо активность при нажатии кнопки.
 

dendy.

Активный
351
66
ну так скинь лог если скрипт крашит
Если я убери что-то около checbox
Lua:
imgui.Checkbox('checkbox'Вот тут если что-то уберу)
То будет
[23:45:42.800818] (error) mimgui.lua: E:\Games\GTA 140K BY DAPO SHOW\moonloader\mimgui.lua:45: wrong number of arguments for function call
stack traceback:
[C]: in function 'Checkbox'
E:\Games\GTA 140K BY DAPO SHOW\moonloader\mimgui.lua:45: in function '_draw'
...mes\GTA 140K BY DAPO SHOW\moonloader\lib\mimgui\init.lua:107: in function <...mes\GTA 140K BY DAPO SHOW\moonloader\lib\mimgui\init.lua:91>
[23:45:42.812819] (error) mimgui.lua: Script died due to an error. (0193BBDC)
А если что-то там есть то крашит самп
 

lorgon

Известный
657
268
Если я убери что-то около checbox
Lua:
imgui.Checkbox('checkbox'Вот тут если что-то уберу)
То будет
[23:45:42.800818] (error) mimgui.lua: E:\Games\GTA 140K BY DAPO SHOW\moonloader\mimgui.lua:45: wrong number of arguments for function call
stack traceback:
[C]: in function 'Checkbox'
E:\Games\GTA 140K BY DAPO SHOW\moonloader\mimgui.lua:45: in function '_draw'
...mes\GTA 140K BY DAPO SHOW\moonloader\lib\mimgui\init.lua:107: in function <...mes\GTA 140K BY DAPO SHOW\moonloader\lib\mimgui\init.lua:91>
[23:45:42.812819] (error) mimgui.lua: Script died due to an error. (0193BBDC)
А если что-то там есть то крашит самп
Почитай.

Lua:
local bool = imgui.new.bool(false)

imgui.Checkbox('checkbox', bool)
 

Nicolas

Активный
114
66
How to convert "listString" to number, not a string?

Lua:
local list = {}

for _, ped in ipairs (getAllChars()) do
    if ped ~= PLAYER_PED then
        local res, id = sampGetPlayerIdByCharHandle(ped)
        if res and not sampIsPlayerNpc(id) then
            table.insert(list, id)
        end
    end
end

--Convert this to a number, instead a string
local listString = table.concat(list," ")
local listString = tonumber(table.concat(list," "))
 
  • Нравится
Реакции: halfastrc

YourAssistant

Участник
144
17
В ini можно как-то записать аналог такой таблицы?
Lua:
table = {
["1"] = {
{"1"},
{"1", "2", "3"},
}
}
 

sat0ry

Известный
1,089
290
lua:
require 'moonloader'
local sampev = require 'lib.samp.events'
local memory = require 'memory'

local imgui = require('imgui')
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local inicfg = require 'inicfg'
local directIni = 'ahelper.ini'
local ini = inicfg.load(inicfg.load({
    cheats = {
        clickwarp = false
    },
}, directIni))
inicfg.save(ini, directIni)

local clickwarp = imgui.ImBool(ini.cheats.clickwarp)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand('menu', function()
        window.v = not window.v
        imgui.Process = window.v
    end)
    
   wait(-1)
end

function imgui.OnDrawFrame()
    if not window.v then
        imgui.Process = false
    end

    if window.v then
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 1000, 600 -- WINDOW SIZE
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2 - sizeX / 2, resY / 2 - sizeY / 2), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Menu', window, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove)
        if imgui.Checkbox('ClickWarp', clickwarp) then
            if clickwarp.v then
                while isPauseMenuActive() do
                    if cursorEnabled then
                        showCursor(false)
                    end
                    wait(100)
                 end
                 if isKeyDown(VK_MBUTTON) then
                     cursorEnabled = not cursorEnabled
                     click_warp()
                     showCursor(cursorEnabled)
                     while isKeyDown(VK_MBUTTON) do wait(80) end
                 end
                 save()
            end
            save()
        end
        imgui.End()
    end
end

function save()
    ini.cheats.clickwarp = clickwarp.v
    inicfg.save(ini, directIni)
end

function onScriptTerminate(script, quit)
    if script == thisScript() then
        imgui.Process = false
        imgui.ShowCursor = false
        showCursor(false, false)
    end
end

function showCursor(toggle)
    if toggle then
      sampSetCursorMode(CMODE_LOCKCAM)
    else
      sampToggleCursor(false)
    end
    cursorEnabled = toggle
end

function teleportPlayer(x, y, z)
    if isCharInAnyCar(playerPed) then
      setCharCoordinates(playerPed, x, y, z)
    end
    setCharCoordinatesDontResetAnim(playerPed, x, y, z)
end

function removePointMarker()
    if pointMarker then
      removeUser3dMarker(pointMarker)
      pointMarker = nil
    end
end

function createPointMarker(x, y, z)
    pointMarker = createUser3dMarker(x, y, z + 0.3, 4)
end

function click_warp()
    lua_thread.create(function()
        while true do
        if cursorEnabled then
          local mode = sampGetCursorMode()
          if mode == 0 then
            showCursor(true)
          end
          local sx, sy = getCursorPos()
          local sw, sh = getScreenResolution()
          if sx >= 0 and sy >= 0 and sx < sw and sy < sh then
            local posX, posY, posZ = convertScreenCoordsToWorld3D(sx, sy, 700.0)
            local camX, camY, camZ = getActiveCameraCoordinates()
            local result, colpoint = processLineOfSight(camX, camY, camZ, posX, posY, posZ,
            true, true, false, true, false, false, false)
            if result and colpoint.entity ~= 0 then
              local normal = colpoint.normal
              local pos = Vector3D(colpoint.pos[1], colpoint.pos[2], colpoint.pos[3]) - (Vector3D(normal[1], normal[2], normal[3]) * 0.1)
              local zOffset = 300
              if normal[3] >= 0.5 then zOffset = 1 end
              local result, colpoint2 = processLineOfSight(pos.x, pos.y, pos.z + zOffset, pos.x, pos.y, pos.z - 0.3,
                true, true, false, true, false, false, false)
              if result then
                pos = Vector3D(colpoint2.pos[1], colpoint2.pos[2], colpoint2.pos[3] + 1)

                local curX, curY, curZ  = getCharCoordinates(playerPed)
                local dist              = getDistanceBetweenCoords3d(curX, curY, curZ, pos.x, pos.y, pos.z)
                local hoffs             = renderGetFontDrawHeight(font)

                sy = sy - 2
                sx = sx - 2
                renderFontDrawText(font, string.format("{FFFFFF}%0.2fm", dist), sx, sy - hoffs, 0xEEEEEEEE)

                local tpIntoCar = nil
                if colpoint.entityType == 2 then
                  local car = getVehiclePointerHandle(colpoint.entity)
                  if doesVehicleExist(car) and (not isCharInAnyCar(playerPed) or storeCarCharIsInNoSave(playerPed) ~= car) then
                    displayVehicleName(sx, sy - hoffs * 2, getNameOfVehicleModel(getCarModel(car)))
                    local color = 0xFFFFFFFF
                    if isKeyDown(VK_RBUTTON) then
                      tpIntoCar = car
                      color = 0xFFFFFFFF
                    end
                    renderFontDrawText(font, "{FFFFFF}Hold right mouse button to teleport into the car", sx, sy - hoffs * 3, color)
                  end
                end

                createPointMarker(pos.x, pos.y, pos.z)

                if isKeyDown(VK_LBUTTON) then
                  if tpIntoCar then
                    if not jumpIntoCar(tpIntoCar) then
                      teleportPlayer(pos.x, pos.y, pos.z)
                      local veh = storeCarCharIsInNoSave(playerPed)
                      local cordsVeh = {getCarCoordinates(veh)}
                      setCarCoordinates(veh, cordsVeh[1], cordsVeh[2], cordsVeh[3])
                    end
                  else
                    if isCharInAnyCar(playerPed) then
                      local norm = Vector3D(colpoint.normal[1], colpoint.normal[2], 0)
                      local norm2 = Vector3D(colpoint2.normal[1], colpoint2.normal[2], colpoint2.normal[3])
                      rotateCarAroundUpAxis(storeCarCharIsInNoSave(playerPed), norm2)
                      pos = pos - norm * 1.8
                      pos.z = pos.z - 1.1
                    end
                    teleportPlayer(pos.x, pos.y, pos.z)
                  end
                  removePointMarker()

                  while isKeyDown(VK_LBUTTON) do wait(0) end
                  showCursor(false)
                end
              end
            end
          end
        end
        wait(0)
        removePointMarker()
        end
    end)
end
При нажатии на чекбокс 'clickwarp', кликварп просто не работает

тоесть нажимая на колесико ничего не происходит
 

shrug228

Активный
212
75
lua:
require 'moonloader'
local sampev = require 'lib.samp.events'
local memory = require 'memory'

local imgui = require('imgui')
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local inicfg = require 'inicfg'
local directIni = 'ahelper.ini'
local ini = inicfg.load(inicfg.load({
    cheats = {
        clickwarp = false
    },
}, directIni))
inicfg.save(ini, directIni)

local clickwarp = imgui.ImBool(ini.cheats.clickwarp)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand('menu', function()
        window.v = not window.v
        imgui.Process = window.v
    end)
  
   wait(-1)
end

function imgui.OnDrawFrame()
    if not window.v then
        imgui.Process = false
    end

    if window.v then
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 1000, 600 -- WINDOW SIZE
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2 - sizeX / 2, resY / 2 - sizeY / 2), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Menu', window, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove)
        if imgui.Checkbox('ClickWarp', clickwarp) then
            if clickwarp.v then
                while isPauseMenuActive() do
                    if cursorEnabled then
                        showCursor(false)
                    end
                    wait(100)
                 end
                 if isKeyDown(VK_MBUTTON) then
                     cursorEnabled = not cursorEnabled
                     click_warp()
                     showCursor(cursorEnabled)
                     while isKeyDown(VK_MBUTTON) do wait(80) end
                 end
                 save()
            end
            save()
        end
        imgui.End()
    end
end

function save()
    ini.cheats.clickwarp = clickwarp.v
    inicfg.save(ini, directIni)
end

function onScriptTerminate(script, quit)
    if script == thisScript() then
        imgui.Process = false
        imgui.ShowCursor = false
        showCursor(false, false)
    end
end

function showCursor(toggle)
    if toggle then
      sampSetCursorMode(CMODE_LOCKCAM)
    else
      sampToggleCursor(false)
    end
    cursorEnabled = toggle
end

function teleportPlayer(x, y, z)
    if isCharInAnyCar(playerPed) then
      setCharCoordinates(playerPed, x, y, z)
    end
    setCharCoordinatesDontResetAnim(playerPed, x, y, z)
end

function removePointMarker()
    if pointMarker then
      removeUser3dMarker(pointMarker)
      pointMarker = nil
    end
end

function createPointMarker(x, y, z)
    pointMarker = createUser3dMarker(x, y, z + 0.3, 4)
end

function click_warp()
    lua_thread.create(function()
        while true do
        if cursorEnabled then
          local mode = sampGetCursorMode()
          if mode == 0 then
            showCursor(true)
          end
          local sx, sy = getCursorPos()
          local sw, sh = getScreenResolution()
          if sx >= 0 and sy >= 0 and sx < sw and sy < sh then
            local posX, posY, posZ = convertScreenCoordsToWorld3D(sx, sy, 700.0)
            local camX, camY, camZ = getActiveCameraCoordinates()
            local result, colpoint = processLineOfSight(camX, camY, camZ, posX, posY, posZ,
            true, true, false, true, false, false, false)
            if result and colpoint.entity ~= 0 then
              local normal = colpoint.normal
              local pos = Vector3D(colpoint.pos[1], colpoint.pos[2], colpoint.pos[3]) - (Vector3D(normal[1], normal[2], normal[3]) * 0.1)
              local zOffset = 300
              if normal[3] >= 0.5 then zOffset = 1 end
              local result, colpoint2 = processLineOfSight(pos.x, pos.y, pos.z + zOffset, pos.x, pos.y, pos.z - 0.3,
                true, true, false, true, false, false, false)
              if result then
                pos = Vector3D(colpoint2.pos[1], colpoint2.pos[2], colpoint2.pos[3] + 1)

                local curX, curY, curZ  = getCharCoordinates(playerPed)
                local dist              = getDistanceBetweenCoords3d(curX, curY, curZ, pos.x, pos.y, pos.z)
                local hoffs             = renderGetFontDrawHeight(font)

                sy = sy - 2
                sx = sx - 2
                renderFontDrawText(font, string.format("{FFFFFF}%0.2fm", dist), sx, sy - hoffs, 0xEEEEEEEE)

                local tpIntoCar = nil
                if colpoint.entityType == 2 then
                  local car = getVehiclePointerHandle(colpoint.entity)
                  if doesVehicleExist(car) and (not isCharInAnyCar(playerPed) or storeCarCharIsInNoSave(playerPed) ~= car) then
                    displayVehicleName(sx, sy - hoffs * 2, getNameOfVehicleModel(getCarModel(car)))
                    local color = 0xFFFFFFFF
                    if isKeyDown(VK_RBUTTON) then
                      tpIntoCar = car
                      color = 0xFFFFFFFF
                    end
                    renderFontDrawText(font, "{FFFFFF}Hold right mouse button to teleport into the car", sx, sy - hoffs * 3, color)
                  end
                end

                createPointMarker(pos.x, pos.y, pos.z)

                if isKeyDown(VK_LBUTTON) then
                  if tpIntoCar then
                    if not jumpIntoCar(tpIntoCar) then
                      teleportPlayer(pos.x, pos.y, pos.z)
                      local veh = storeCarCharIsInNoSave(playerPed)
                      local cordsVeh = {getCarCoordinates(veh)}
                      setCarCoordinates(veh, cordsVeh[1], cordsVeh[2], cordsVeh[3])
                    end
                  else
                    if isCharInAnyCar(playerPed) then
                      local norm = Vector3D(colpoint.normal[1], colpoint.normal[2], 0)
                      local norm2 = Vector3D(colpoint2.normal[1], colpoint2.normal[2], colpoint2.normal[3])
                      rotateCarAroundUpAxis(storeCarCharIsInNoSave(playerPed), norm2)
                      pos = pos - norm * 1.8
                      pos.z = pos.z - 1.1
                    end
                    teleportPlayer(pos.x, pos.y, pos.z)
                  end
                  removePointMarker()

                  while isKeyDown(VK_LBUTTON) do wait(0) end
                  showCursor(false)
                end
              end
            end
          end
        end
        wait(0)
        removePointMarker()
        end
    end)
end
При нажатии на чекбокс 'clickwarp', кликварп просто не работает

тоесть нажимая на колесико ничего не происходит
Тебе уже выше писали, что стоит ознакомиться с основами языка, настоятельно рекомендую все же это сделать. Блок кода, где ты и отслеживаешь нажатие клавиш находится в if wnidow.v then, т.е. когда окно закрыто оно никак не может выполняться.
Условие if imgui.Checkbox() then срабатывает только при смене состояния чекбокса, т.е. когда на него нажали и он стал включен/выключен.
 

sat0ry

Известный
1,089
290
Тебе уже выше писали, что стоит ознакомиться с основами языка, настоятельно рекомендую все же это сделать. Блок кода, где ты и отслеживаешь нажатие клавиш находится в if wnidow.v then, т.е. когда окно закрыто оно никак не может выполняться.
Условие if imgui.Checkbox() then срабатывает только при смене состояния чекбокса, т.е. когда на него нажали и он стал включен/выключен.
Не понимаю с чего ты взял, что я не ознакомлен с основами? Пытался засовывать в while true do -- постоянный цикл, и что ты думаешь? ПРАВИЛЬНО! нихуя не работало.

Прежде чем писать не обдуманную хуету, попробуй сам изменить код