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

sdfy

Известный
349
230
imgui.CenterTextt(u8(fa. ICON_FA_WIFI .. " Time: 123))
что я делаю не так? ( mimgui )
Посмотреть вложение 183392
Используй шрифт для fa icons
 

#SameLine

Активный
417
37
Используй шрифт для fa icons
не тот скрин кинул
1672225005299.png


imgui.CenterTextt(u8(fa. ICON_FA_LOCATION_ARROW.. " Time: 123))

Lua:
local fa = require("fAwesome5")
imgui.OnInitialize(function()
    local config = imgui.ImFontConfig()
    config.MergeMode = true
    local glyph_ranges = imgui.GetIO().Fonts:GetGlyphRangesCyrillic()
    local iconRanges = imgui.new.ImWchar[3](fa.min_range, fa.max_range, 0)
    imgui.GetIO().Fonts:AddFontFromFileTTF('trebucbd.ttf', 14.0, nil, glyph_ranges)
    icon = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 14.0, config, iconRanges)
end)
 
Последнее редактирование:

sdfy

Известный
349
230
не тот скрин кинул
Посмотреть вложение 183393

imgui.CenterTextt(u8(fa. ICON_FA_LOCATION_ARROW.. " Time: 123))

Lua:
local fa = require("fAwesome5")
imgui.OnInitialize(function()
    local config = imgui.ImFontConfig()
    config.MergeMode = true
    local glyph_ranges = imgui.GetIO().Fonts:GetGlyphRangesCyrillic()
    local iconRanges = imgui.new.ImWchar[3](fa.min_range, fa.max_range, 0)
    imgui.GetIO().Fonts:AddFontFromFileTTF('trebucbd.ttf', 14.0, nil, glyph_ranges)
    icon = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 14.0, config, iconRanges)
end)
Lua:
imgui.PushFont(icon)     
imgui.Text(fa.ICON_FA_CLOCK.." "..os.date("%H:%M:%S"))
imgui.PopFont()
1672226469775.png
 
  • Нравится
Реакции: #SameLine

XRLM

Известный
2,553
871
не тот скрин кинул
Посмотреть вложение 183393

imgui.CenterTextt(u8(fa. ICON_FA_LOCATION_ARROW.. " Time: 123))

Lua:
local fa = require("fAwesome5")
imgui.OnInitialize(function()
    local config = imgui.ImFontConfig()
    config.MergeMode = true
    local glyph_ranges = imgui.GetIO().Fonts:GetGlyphRangesCyrillic()
    local iconRanges = imgui.new.ImWchar[3](fa.min_range, fa.max_range, 0)
    imgui.GetIO().Fonts:AddFontFromFileTTF('trebucbd.ttf', 14.0, nil, glyph_ranges)
    icon = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 14.0, config, iconRanges)
end)
если у тебя мимгуи, то лучше юзать 6 версию иконок.
 
  • Клоун
Реакции: Air_Official

Anti...

Активный
263
26
CHAMS:
script_author('The Spark / Custom Galaxy')
script_name('Chams')

local ffi = require("ffi")
ffi.cdef([[
    typedef unsigned long DWORD;

    struct d3ddeviceVTBL {
        void *QueryInterface;
        void *AddRef;
        void *Release;
        void *TestCooperativeLevel;
        void *GetAvailableTextureMem;
        void *EvictManagedResources;
        void *GetDirect3D;
        void *GetDeviceCaps;
        void *GetDisplayMode;
        void *GetCreationParameters;
        void *SetCursorProperties;
        void *SetCursorPosition;
        void *ShowCursor;
        void *CreateAdditionalSwapChain;
        void *GetSwapChain;
        void *GetNumberOfSwapChains;
        void *Reset;
        void *Present;
        void *GetBackBuffer;
        void *GetRasterStatus;
        void *SetDialogBoxMode;
        void *SetGammaRamp;
        void *GetGammaRamp;
        void *CreateTexture;
        void *CreateVolumeTexture;
        void *CreateCubeTexture;
        void *CreateVertexBuffer;
        void *CreateIndexBuffer;
        void *CreateRenderTarget;
        void *CreateDepthStencilSurface;
        void *UpdateSurface;
        void *UpdateTexture;
        void *GetRenderTargetData;
        void *GetFrontBufferData;
        void *StretchRect;
        void *ColorFill;
        void *CreateOffscreenPlainSurface;
        void *SetRenderTarget;
        void *GetRenderTarget;
        void *SetDepthStencilSurface;
        void *GetDepthStencilSurface;
        void *BeginScene;
        void *EndScene;
        void *Clear;
        void *SetTransform;
        void *GetTransform;
        void *MultiplyTransform;
        void *SetViewport;
        void *GetViewport;
        void *SetMaterial;
        void *GetMaterial;
        void *SetLight;
        void *GetLight;
        void *LightEnable;
        void *GetLightEnable;
        void *SetClipPlane;
        void *GetClipPlane;
        void *SetRenderState;
        void *GetRenderState;
        void *CreateStateBlock;
        void *BeginStateBlock;
        void *EndStateBlock;
        void *SetClipStatus;
        void *GetClipStatus;
        void *GetTexture;
        void *SetTexture;
        void *GetTextureStageState;
        void *SetTextureStageState;
        void *GetSamplerState;
        void *SetSamplerState;
        void *ValidateDevice;
        void *SetPaletteEntries;
        void *GetPaletteEntries;
        void *SetCurrentTexturePalette;
        void *GetCurrentTexturePalette;
        void *SetScissorRect;
        void *GetScissorRect;
        void *SetSoftwareVertexProcessing;
        void *GetSoftwareVertexProcessing;
        void *SetNPatchMode;
        void *GetNPatchMode;
        void *DrawPrimitive;
        void* DrawIndexedPrimitive;
        void *DrawPrimitiveUP;
        void *DrawIndexedPrimitiveUP;
        void *ProcessVertices;
        void *CreateVertexDeclaration;
        void *SetVertexDeclaration;
        void *GetVertexDeclaration;
        void *SetFVF;
        void *GetFVF;
        void *CreateVertexShader;
        void *SetVertexShader;
        void *GetVertexShader;
        void *SetVertexShaderConstantF;
        void *GetVertexShaderConstantF;
        void *SetVertexShaderConstantI;
        void *GetVertexShaderConstantI;
        void *SetVertexShaderConstantB;
        void *GetVertexShaderConstantB;
        void *SetStreamSource;
        void *GetStreamSource;
        void *SetStreamSourceFreq;
        void *GetStreamSourceFreq;
        void *SetIndices;
        void *GetIndices;
        void *CreatePixelShader;
        void *SetPixelShader;
        void *GetPixelShader;
        void *SetPixelShaderConstantF;
        void *GetPixelShaderConstantF;
        void *SetPixelShaderConstantI;
        void *GetPixelShaderConstantI;
        void *SetPixelShaderConstantB;
        void *GetPixelShaderConstantB;
        void *DrawRectPatch;
        void *DrawTriPatch;
        void *DeletePatch;
    };

    struct d3ddevice {
        struct d3ddeviceVTBL** vtbl;
    };
]])

local pDevice = ffi.cast("struct d3ddevice*", 0xC97C28)
local SetTextureStageState = ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned long)", pDevice.vtbl[0].SetTextureStageState)
local GetTextureStageState = ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned int*)", pDevice.vtbl[0].GetTextureStageState)

local dwConstant = ffi.new("unsigned int[1]")
local dwARG0 = ffi.new("unsigned int[1]")
local dwARG1 = ffi.new("unsigned int[1]")
local dwARG2 = ffi.new("unsigned int[1]")

local cast = ffi.cast("void(__thiscall*)(void*)", 0x59F180)

local prefix = "{00AAFF}["..thisScript().name.."]{FFFFFF}: "
local prefixerr = "{ff0000}["..thisScript().name.."]{FFFFFF}: "
local ChamsQuery = {}

function main()
    while not isSampAvailable() do wait(0) end
    if not isSampfuncsLoaded() and not isCleoLoaded() then return end

    while not sampIsLocalPlayerSpawned() do wait(0) end

    
    while true do wait(0)
        for k,v in pairs(getAllChars()) do
            if v ~= PLAYER_PED then
                if ChamsQuery[v] then
                    if not isCharOnScreen(v) then           
                        RemoveFromChamsQuery(v)
                    end
                elseif isCharOnScreen(v) then
                    AddPlayerToChamsQuery(v, -1)
                end
            end
        end
    end
end

function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

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

function onD3DPresent()
    --if not sampIsScoreboardOpen() and not isPauseMenuActive() and sampIsLocalPlayerSpawned() then
        for key, color in pairs(ChamsQuery) do
            local pPed = getCharPointer(key)
            if pPed ~= 0 then
                GetTextureStageState(pDevice, 0, 32, dwConstant)
                GetTextureStageState(pDevice, 0, 26, dwARG0)
                GetTextureStageState(pDevice, 0, 2,  dwARG1)--
                GetTextureStageState(pDevice, 0, 3,  dwARG2)

                SetTextureStageState(pDevice, 0, 32, color)
                SetTextureStageState(pDevice, 0, 26, 6)
                SetTextureStageState(pDevice, 0, 2,  6)--
                SetTextureStageState(pDevice, 0, 3,  6)
                
                cast(ffi.cast("void*", pPed))
              
                SetTextureStageState(pDevice, 0, 32, dwConstant[0])
                SetTextureStageState(pDevice, 0, 26, dwARG0[0])
                SetTextureStageState(pDevice, 0, 2,  dwARG1[0])--
                SetTextureStageState(pDevice, 0, 3,  dwARG2[0])
            end
        end
    --end
end

Есть вот такой код, это ВХ CHAMS. Проблема в том, что он налаживает текстуру на все скины, игроков и нпс, я пробовал сделать что бы видно было только игроков этим, но ничего не получилось, подскажите, что делать?:
Код:
for i = 0, sampGetMaxPlayerId(true) do
    if not sampIsPlayerNpc(i) then
        local find, handle = sampGetCharHandleBySampPlayerId(i)
        if find then
        
        end
    end
end

CHAMS:
script_author('The Spark / Custom Galaxy')
script_name('Chams')

local ffi = require("ffi")
ffi.cdef([[
    typedef unsigned long DWORD;

    struct d3ddeviceVTBL {
        void *QueryInterface;
        void *AddRef;
        void *Release;
        void *TestCooperativeLevel;
        void *GetAvailableTextureMem;
        void *EvictManagedResources;
        void *GetDirect3D;
        void *GetDeviceCaps;
        void *GetDisplayMode;
        void *GetCreationParameters;
        void *SetCursorProperties;
        void *SetCursorPosition;
        void *ShowCursor;
        void *CreateAdditionalSwapChain;
        void *GetSwapChain;
        void *GetNumberOfSwapChains;
        void *Reset;
        void *Present;
        void *GetBackBuffer;
        void *GetRasterStatus;
        void *SetDialogBoxMode;
        void *SetGammaRamp;
        void *GetGammaRamp;
        void *CreateTexture;
        void *CreateVolumeTexture;
        void *CreateCubeTexture;
        void *CreateVertexBuffer;
        void *CreateIndexBuffer;
        void *CreateRenderTarget;
        void *CreateDepthStencilSurface;
        void *UpdateSurface;
        void *UpdateTexture;
        void *GetRenderTargetData;
        void *GetFrontBufferData;
        void *StretchRect;
        void *ColorFill;
        void *CreateOffscreenPlainSurface;
        void *SetRenderTarget;
        void *GetRenderTarget;
        void *SetDepthStencilSurface;
        void *GetDepthStencilSurface;
        void *BeginScene;
        void *EndScene;
        void *Clear;
        void *SetTransform;
        void *GetTransform;
        void *MultiplyTransform;
        void *SetViewport;
        void *GetViewport;
        void *SetMaterial;
        void *GetMaterial;
        void *SetLight;
        void *GetLight;
        void *LightEnable;
        void *GetLightEnable;
        void *SetClipPlane;
        void *GetClipPlane;
        void *SetRenderState;
        void *GetRenderState;
        void *CreateStateBlock;
        void *BeginStateBlock;
        void *EndStateBlock;
        void *SetClipStatus;
        void *GetClipStatus;
        void *GetTexture;
        void *SetTexture;
        void *GetTextureStageState;
        void *SetTextureStageState;
        void *GetSamplerState;
        void *SetSamplerState;
        void *ValidateDevice;
        void *SetPaletteEntries;
        void *GetPaletteEntries;
        void *SetCurrentTexturePalette;
        void *GetCurrentTexturePalette;
        void *SetScissorRect;
        void *GetScissorRect;
        void *SetSoftwareVertexProcessing;
        void *GetSoftwareVertexProcessing;
        void *SetNPatchMode;
        void *GetNPatchMode;
        void *DrawPrimitive;
        void* DrawIndexedPrimitive;
        void *DrawPrimitiveUP;
        void *DrawIndexedPrimitiveUP;
        void *ProcessVertices;
        void *CreateVertexDeclaration;
        void *SetVertexDeclaration;
        void *GetVertexDeclaration;
        void *SetFVF;
        void *GetFVF;
        void *CreateVertexShader;
        void *SetVertexShader;
        void *GetVertexShader;
        void *SetVertexShaderConstantF;
        void *GetVertexShaderConstantF;
        void *SetVertexShaderConstantI;
        void *GetVertexShaderConstantI;
        void *SetVertexShaderConstantB;
        void *GetVertexShaderConstantB;
        void *SetStreamSource;
        void *GetStreamSource;
        void *SetStreamSourceFreq;
        void *GetStreamSourceFreq;
        void *SetIndices;
        void *GetIndices;
        void *CreatePixelShader;
        void *SetPixelShader;
        void *GetPixelShader;
        void *SetPixelShaderConstantF;
        void *GetPixelShaderConstantF;
        void *SetPixelShaderConstantI;
        void *GetPixelShaderConstantI;
        void *SetPixelShaderConstantB;
        void *GetPixelShaderConstantB;
        void *DrawRectPatch;
        void *DrawTriPatch;
        void *DeletePatch;
    };

    struct d3ddevice {
        struct d3ddeviceVTBL** vtbl;
    };
]])

local pDevice = ffi.cast("struct d3ddevice*", 0xC97C28)
local SetTextureStageState = ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned long)", pDevice.vtbl[0].SetTextureStageState)
local GetTextureStageState = ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned int*)", pDevice.vtbl[0].GetTextureStageState)

local dwConstant = ffi.new("unsigned int[1]")
local dwARG0 = ffi.new("unsigned int[1]")
local dwARG1 = ffi.new("unsigned int[1]")
local dwARG2 = ffi.new("unsigned int[1]")

local cast = ffi.cast("void(__thiscall*)(void*)", 0x59F180)

local prefix = "{00AAFF}["..thisScript().name.."]{FFFFFF}: "
local prefixerr = "{ff0000}["..thisScript().name.."]{FFFFFF}: "
local ChamsQuery = {}

function main()
    while not isSampAvailable() do wait(0) end
    if not isSampfuncsLoaded() and not isCleoLoaded() then return end

    while not sampIsLocalPlayerSpawned() do wait(0) end

   
    while true do wait(0)
        for k,v in pairs(getAllChars()) do
            if v ~= PLAYER_PED then
                if ChamsQuery[v] then
                    if not isCharOnScreen(v) then          
                        RemoveFromChamsQuery(v)
                    end
                elseif isCharOnScreen(v) then
                    AddPlayerToChamsQuery(v, -1)
                end
            end
        end
    end
end

function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

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

function onD3DPresent()
    --if not sampIsScoreboardOpen() and not isPauseMenuActive() and sampIsLocalPlayerSpawned() then
        for key, color in pairs(ChamsQuery) do
            local pPed = getCharPointer(key)
            if pPed ~= 0 then
                GetTextureStageState(pDevice, 0, 32, dwConstant)
                GetTextureStageState(pDevice, 0, 26, dwARG0)
                GetTextureStageState(pDevice, 0, 2,  dwARG1)--
                GetTextureStageState(pDevice, 0, 3,  dwARG2)

                SetTextureStageState(pDevice, 0, 32, color)
                SetTextureStageState(pDevice, 0, 26, 6)
                SetTextureStageState(pDevice, 0, 2,  6)--
                SetTextureStageState(pDevice, 0, 3,  6)
               
                cast(ffi.cast("void*", pPed))
             
                SetTextureStageState(pDevice, 0, 32, dwConstant[0])
                SetTextureStageState(pDevice, 0, 26, dwARG0[0])
                SetTextureStageState(pDevice, 0, 2,  dwARG1[0])--
                SetTextureStageState(pDevice, 0, 3,  dwARG2[0])
            end
        end
    --end
end

Есть вот такой код, это ВХ CHAMS. Проблема в том, что он налаживает текстуру на все скины, игроков и нпс, я пробовал сделать что бы видно было только игроков этим, но ничего не получилось, подскажите, что делать?:
Код:
for i = 0, sampGetMaxPlayerId(true) do
    if not sampIsPlayerNpc(i) then
        local find, handle = sampGetCharHandleBySampPlayerId(i)
        if find then
       
        end
    end
end
Решил вот так в бесконечном цикле
Код:
for i = 0, sampGetMaxPlayerId(true) do
            if not sampIsPlayerNpc(i) then
                local find, handle = sampGetCharHandleBySampPlayerId(i)
                if find then
                    if ChamsQuery[handle] then
                        if not isCharOnScreen(handle) then           
                            RemoveFromChamsQuery(handle)
                        end
                    elseif isCharOnScreen(handle) then
                        AddPlayerToChamsQuery(handle, -1)
                    end
                end
            end
        end

Как сделать проверку на видимость игрока? А точнее проверять, находится ли игрок за текстурой, звучит бредово. Мне для ВХ, если игрок за домом - цвет будет красный, если в видимости - то белый.
Код:
for i = 0, sampGetMaxPlayerId(true) do
            if not sampIsPlayerNpc(i) then
                local find, handle = sampGetCharHandleBySampPlayerId(i)
                if find then
                    if isCharOnScreen(handle) then
                        local myPos = {GetBodyPartCoordinates(3, PLAYER_PED)}
                        local enPos = {GetBodyPartCoordinates(3, handle)}
                        if (isLineOfSightClear(myPos[1], myPos[2], myPos[3], enPos[1], enPos[2], enPos[3], true, true, false, true, true)) then
                            color = 0xFFFFFFFF
                            sampAddChatMessage('Игрок', color)
                        else
                            color = 0xFF5500FF
                            sampAddChatMessage('НЕ Игрок', color)
                        end
                    end
                end
            end
        end
Вот так не подойдёт
 
Последнее редактирование:

wizardryv11

Новичок
1
0
в луа есть что-то тип SetObjectMaterialText? onSetObjectMaterialText ждать не подходит т.к. нужно из него ждать завершения следующего присваивания материального текста. Короче нужно именно установить текст, а не обрабатывать событие.
 

хуега)

РП игрок
Модератор
2,567
2,264
крашит скрипт после того как умирает/пропадает/кикается игрок который выбран
вот код
LUA:
local ev = require ("samp.events")

local tag = '{0000FF} [OCHKORVANKA BY Bylochka] {000000}- '
local rvanka = false
local m = 0
local roll = 0
local last_sync = os.clock()

function main()
    if not isSampAvailable() then return false end

    sampAddChatMessage(tag .. '{3333ff}Rvanka {ffffff}успешно загружена.', -1)

    sampRegisterChatCommand('rv', function(id)
        if not id or not tonumber(id) then
            rvanka = false
            sampAddChatMessage(tag .. '{ffffff}Не верный ид', -1)
            m = 0
            roll = 0
        end
        if not isCharInAnyCar(PLAYER_PED) then
            sampAddChatMessage(tag .. '{ffffff}Вы не в авто', -1)
            rvanka = false
            m = 0
            roll = 0
        end
        local result,ped = sampGetCharHandleBySampPlayerId(id)
        if result then
            if doesCharExist(ped) then
                local px, py, pz = getCharCoordinates(ped)
                local ax, ay, az = getCharCoordinates(PLAYER_PED)
                local dist = getDistanceBetweenCoords3d(px, py, pz, ax, ay, az)
                if dist <= 29 then
                    _, pid = sampGetPlayerIdByCharHandle(ped)
                    victimPed = ped
                    rvanka = not rvanka
                    printStringNow(rvanka and 'Rvanka - ~g~ON' or 'Rvanka - ~r~OFF',1000)
                end
            end
        end
        if not ped then
            rvanka = false
            m = 0
            roll = 0
        end
    end)
    while true do wait(0)
        if not pid then
            rvanka = false
            m = 0
            roll = 0
        end
        if rvanka then
            if os.clock() - last_sync > 1/15 then
                roll = roll + 30
                if roll >= 360 then roll = 0 end
                pcall(sampForceVehicleSync, select(2, sampGetVehicleIdByCarHandle(storeCarCharIsInNoSave(PLAYER_PED))))
            end
            if not pid then
                rvanka = false
                m = 0
                roll = 0
            end
        end
    end
end
lua_thread.create(function()
    while true do wait(0)
        if rvanka then
            m = m + 0.1
            if m >= 1.65 then
                m = 1.65
            end
            wait(200)
        end
    end
end)
function ev.onSendVehicleSync(data)
    if rvanka then
        local px, py, pz = getCharCoordinates(victimPed)
        local ax, ay, az = getCharCoordinates(PLAYER_PED)
        local dist = getDistanceBetweenCoords3d(px, py, pz, ax, ay, az)
        if dist <= 39 then
            if sampIsPlayerConnected(pid) and sampGetCharHandleBySampPlayerId(pid) then
                data.position = {px,py,pz - 0.7}
                data.quaternion[0] = calculate_quat(roll)
                data.quaternion[1] = calculate_quat(roll)
                data.quaternion[2] = calculate_quat(roll)
                data.quaternion[3] = calculate_quat(roll)
                data.moveSpeed = getMoveSpeed(getCharHeading(playerPed), m)
                data.moveSpeed.z = 0.25
            end
        else
            rvanka = false
            m = 0
            roll = 0
            sampAddChatMessage("Игрок сместился слишком далеко.", -1)
        end
        if not pid then
            rvanka = false
            m = 0
            roll = 0
        end
    end
end

function getMoveSpeed(head, speed)
    move = {
        z = 0,
        x = math.sin(-math.rad(head)) * speed,
        y = math.cos(-math.rad(head)) * speed
    }
    moveSpeed = move

    return moveSpeed
end
function calculate_quat(angle)
    angle = math.rad(angle >= 180 and angle - 360 or angle)
 
    local c2 = math.cos(angle / 2)
    local s2 = math.sin(angle / 2)
 
    return 1 * c2 * 1 - 0 * s2 * 0, -(1 * s2 * 1 - 0 * c2 * 0)
end
function samp_create_sync_data(sync_type, copy_from_player)
    local ffi = require 'ffi' local sampfuncs = require 'sampfuncs'
    local raknet = require 'samp.raknet' copy_from_player = copy_from_player or true
    local sync_traits = {
        player = {'PlayerSyncData', raknet.PACKET.PLAYER_SYNC, sampStorePlayerOnfootData},
        vehicle = {'VehicleSyncData', raknet.PACKET.VEHICLE_SYNC, sampStorePlayerIncarData},
        passenger = {'PassengerSyncData', raknet.PACKET.PASSENGER_SYNC, sampStorePlayerPassengerData},
        aim = {'AimSyncData', raknet.PACKET.AIM_SYNC, sampStorePlayerAimData},
        trailer = {'TrailerSyncData', raknet.PACKET.TRAILER_SYNC, sampStorePlayerTrailerData},
        unoccupied = {'UnoccupiedSyncData', raknet.PACKET.UNOCCUPIED_SYNC, nil},
        bullet = {'BulletSyncData', raknet.PACKET.BULLET_SYNC, nil},
        spectator = {'SpectatorSyncData', raknet.PACKET.SPECTATOR_SYNC, nil}
    }
    local sync_info = sync_traits[sync_type] local data_type = 'struct ' .. sync_info[1]
    local data = ffi.new(data_type, {})
    local raw_data_ptr = tonumber(ffi.cast('uintptr_t', ffi.new(data_type .. '*', data)))
    if copy_from_player then local copy_func = sync_info[3]
        if copy_func then local _, player_id if copy_from_player == true then
            _, player_id = sampGetPlayerIdByCharHandle(PLAYER_PED) else
            player_id = tonumber(copy_from_player) end
            copy_func(player_id, raw_data_ptr) end
    end
    local func_send = function() local bs = raknetNewBitStream()
        raknetBitStreamWriteInt8(bs, sync_info[2])
        raknetBitStreamWriteBuffer(bs, raw_data_ptr, ffi.sizeof(data))
        raknetSendBitStreamEx(bs, sampfuncs.HIGH_PRIORITY, sampfuncs.UNRELIABLE_SEQUENCED, 1)
        raknetDeleteBitStream(bs)
    end
    local mt = {
        __index = function(t, index) return data[index] end,
        __newindex = function(t, index, value) data[index] = value
        end
    }
    return setmetatable({send = func_send}, mt)
end

лог
перед получением корд добавь проверку на существование чела
 
  • Нравится
Реакции: shibaTaidjy

bedolaga123123

Новичок
22
5
Ребят, приветик, подскажите, пожалуйста.
Как сделать по команде, чтобы флудилось /showpass id ? Например, команда /stoper id, и что бы по этой команде человеку постояно показывался /showpass
 

хуега)

РП игрок
Модератор
2,567
2,264
Ребят, приветик, подскажите, пожалуйста.
Как сделать по команде, чтобы флудилось /showpass id ? Например, команда /stoper id, и что бы по этой команде человеку постояно показывался /showpass

Lua:
-- вне функций

local bool = false
local pid = nil

-- в main()

sampRegisterChatCommand("stoper", function(id)  
    if id:match("%d+") then
        pid = id
        bool = not bool
    end
end)

while true do wait(0)
    if bool and pid ~= nil then
        sampSendChat(string.format("/showpass", pid))
    end
end