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

Baika

Участник
53
27
Помогите мне чайнику, как сделать так чтобы после того как бот достиг координат 3 д текста он бежал на обычные координаты например такие: -104.59384918213 99.912292480469 и так по кругу
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("fan",function () act = not act sampAddChatMessage(act and "Активирован" or "Деактивирован",-1 )end)
    while true do wait(0)
        for id = 0, 2048 do
            if sampIs3dTextDefined(id) then
                local text, _, x, y, _, _, _, _, _ = sampGet3dTextInfoById(id)
                if text:find("Куст") and act then
                    runToPoint(x,y)
                end
             
            end
        end
       
    end
end


function runToPoint(tox, toy)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local angle = getHeadingFromVector2d(tox - x, toy - y)
    local xAngle = math.random(-50, 50)/100
    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
    stopRun = false
    while getDistanceBetweenCoords2d(x, y, tox, toy) > 0.8 and act  do
        result, text, color, posX, posY, posZ, distance, ignoreWalls, player, vehicle = Search3Dtext(x, y, z, 3, "Куст")
        if result then
            break
        end
       
        setGameKeyState(1, -255)
        setGameKeyState(16, 1)
        wait(1)
        x, y, z = getCharCoordinates(PLAYER_PED)
        angle = getHeadingFromVector2d(tox - x, toy - y)
        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
        if stopRun then
            stopRun = false
            break
        end
    end
end
function Search3Dtext(x, y, z, radius, patern)
    local text = ""
    local color = 0
    local posX = 0.0
    local posY = 0.0
    local posZ = 0.0
    local distance = 0.0
    local ignoreWalls = false
    local player = -1
    local vehicle = -1
    local result = false

    for id = 0, 2048 do
        if sampIs3dTextDefined(id) then
            local text2, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2 = sampGet3dTextInfoById(id)
            if getDistanceBetweenCoords3d(x, y, z, posX2, posY2, posZ2) < radius then
               
                if string.len(patern) ~= 0 then
                    if string.match(text2, patern, 0) ~= nil then result = true end
                else
                    result = true
                end
                if result then
                    text = text2
                    color = color2
                    posX = posX2
                    posY = posY2
                    posZ = posZ2
                    distance = distance2
                    ignoreWalls = ignoreWalls2
                    player = player2
                    vehicle = vehicle2
                    radius = getDistanceBetweenCoords3d(x, y, z, posX, posY, posZ)
                end
            end
        end
    end

    return result, text, color, posX, posY, posZ, distance, ignoreWalls, player, vehicle
end
 

uvie

Известный
271
54

in the video, you can see how a green tracer appears and tracer numbers at the end, [machines] this is the work of thieves, while driving, the thief must find a certain hidden machine, would it be possible to reproduce the same tracer? 2. Find By car number plate
How i can make it? I only have 2 snipperS

Lua:
:SAMPGetCarNumberPlateByVehicleID

{
    0.3.7 - R5

    0AB1: @SAMPGetCarNumberPlateByVehicleID 1 VehicleID 1249 _Returned: NumberPlate 0@
}
IF 0AA2: 10@ = "samp.dll"
THEN
    10@ += 0x26EB94 // SAMP_INFO_OFFSET
    0A8D: 10@ readMem 10@ sz 4 vp 0
    10@ += 0x3DE // SAMP_PPOOLS_OFFSET
    0A8D: 10@ readMem 10@ sz 4 vp 0
    10@ += 0x0 // SAMP_PPOOL_VEHICLE_OFFSET
    0A8D: 10@ readMem 10@ sz 4 vp 0
    0@ *= 0x4 // VEHICLE_ID * 0x14
    0@ += 0x1134
    005A: 10@ += 0@
    0A8D: 10@ = readMem 10@ sz 4 vp 0
    10@ += 0x93 // SAMP_VEHICLE_NUMBER_PLATE_OFFSET
    0A8D: 4@ = readMem 10@ sz 1 vp 0
    IF 4@ > 0
    THEN 0485:  return_true
    ELSE
        059A:  return_false
        10@ = 0
    END
END
0AB2: ret 1 10@



Lua:
:SAMPGetVehicleIDbyCarHandle // if 0AB1: @SAMPGetVehicleIDbyCarHandle 1 _OfCarHandle 0@ _StoreVehicleID 29@
if 0AA2: 31@ = load_dynamic_library "samp.dll" // pSAMPBase // no need to Free Memory
then
    31@ += 0x26EB94
    0A8D: 31@ = read_memory 31@ size 4 virtual_protect 0 // stSAMPInfo
    if 31@ > 0
    then
        31@ += 0x3DE
        0A8D: 31@ = read_memory 31@ size 4 virtual_protect 0 // stSAMPPools
        if 31@ > 0
        then
            31@ += 0x0
            0A8D: 31@ = read_memory 31@ size 4 virtual_protect 0 // stVehiclePool
            if 31@ > 0
            then
                0A97: 30@ = vehicle 0@ struct
                for 29@ = 0 to 8000 step 4 // vehicle index = max vehicle * 4 = 2000 * 4
                    0A8E: 28@ = 29@ + 31@
                    0A8E: 27@ = 28@ + 0x3074
                    0A8D: 27@ = read_memory 27@ size 4 virtual_protect 0 // iIsListed
                    if 27@ > 0
                    then
                        0A8E: 27@ = 28@ + 0x1134
                        0A8D: 27@ = read_memory 27@ size 4 virtual_protect 0 // pSAMP_Vehicle
                        if 27@ > 0
                        then
                            27@ += 0x4C
                            0A8D: 26@ = read_memory 27@ size 4 virtual_protect 0 // pGTA_Vehicle
                            if 003B: 26@ == 30@  // our vehicle matched
                            then
                                29@ /= 4
                                0485:  return_true
                                ret 1 29@ // I now Got the Vehicle ID
                            end
                        end
                    end
                end
            end
        end
    end
end
059A:  return_false
ret 1 -1 // null Vehicle ID





Lua:
function FindVehicleByNumberPlate(targetNumberPlate)
    local sampDLL = loadLibrary("samp.dll")
    if sampDLL then
        local stSAMPInfo = readMemory(sampDLL + 0x26EB94, 4)
        if stSAMPInfo > 0 then
            local stSAMPPools = readMemory(stSAMPInfo + 0x3DE, 4)
            if stSAMPPools > 0 then
                local stVehiclePool = readMemory(stSAMPPools + 0x0, 4)
                if stVehiclePool > 0 then
                    for i = 0, 2000 do
                        local vehicleIndex = i * 4
                        local vehicleAddr = readMemory(stVehiclePool + vehicleIndex + 0x1134, 4)
                        if vehicleAddr > 0 then
                            local numberPlate = readMemory(vehicleAddr + 0x93, 1)
                            if numberPlate == targetNumberPlate then
                                return vehicleAddr
                            end
                        end
                    end
                end
            end
        end
    end
    return nil
end

function CreateTracerToVehicle(vehicleAddr)
    if vehicleAddr then
        local vehiclePosition = GetVehiclePosition(vehicleAddr)
        local playerPosition = GetPlayerPosition()
        if vehiclePosition and playerPosition then
            local direction = {
                x = vehiclePosition.x - playerPosition.x,
                y = vehiclePosition.y - playerPosition.y,
                z = vehiclePosition.z - playerPosition.z
            }

            local magnitude = math.sqrt(direction.x^2 + direction.y^2 + direction.z^2)
            direction.x = direction.x / magnitude
            direction.y = direction.y / magnitude
            direction.z = direction.z / magnitude

            RenderTracer(playerPosition, direction, "green", magnitude)
        end
    else
        print("Vehicle not found.")
    end
end

local numberPlateToFind = "ABC123"
local vehicleAddress = FindVehicleByNumberPlate(numberPlateToFind)

if vehicleAddress then
    CreateTracerToVehicle(vehicleAddress)
else
    print("Vehicle with number plate ".. numberPlateToFind .." not found.")
end
 

Вложения

  • image.png
    image.png
    204.9 KB · Просмотры: 13
  • Эм
Реакции: Baika

Samirca

Участник
152
19
Если какой-то авто скролл? я заколебался уже ждать 5 секунд пока перезарядится оружие
 

Klimer

Активный
161
44
Как после бега к 3д тексту сделать так что бы он останавливался на секунд 20, а после пошел на другой 3д текст
Lua:
local run = false

function runToPoint(tox, toy)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local angle = getHeadingFromVector2d(tox - x, toy - y)
    local xAngle = math.random(-50, 50)/100
    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
    stopRun = false
    while getDistanceBetweenCoords2d(x, y, tox, toy) > 0.8 do
        setGameKeyState(1, -255)
        --setGameKeyState(16, 1)
        wait(1)
        x, y, z = getCharCoordinates(PLAYER_PED)
        angle = getHeadingFromVector2d(tox - x, toy - y)
        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
        if stopRun then
            stopRun = false
            break
        end
    end
end

function main()
    repeat wait(0) until isSampAvailable()
        sampRegisterChatCommand('cmds',function()
            run = not run
            sampAddChatMessage('Состояние: ' ..(run and 'Вкл' or 'Выкл'),-1)
        end)

    while true do wait(0)
        if run then
            for i = 0,2048 do
                if sampIs3dTextDefined(i) then
                    text, clr, posX, posY, posZ, dist, wh, plid, vehid = sampGet3dTextInfoById(i)
                    if string.match(text,'урожая') then
                        runToPoint(posX,posY)
                        run = false
                    end
                end
            end
        end
    end
end
 

fokichevskiy

Известный
461
237

in the video, you can see how a green tracer appears and tracer numbers at the end, [machines] this is the work of thieves, while driving, the thief must find a certain hidden machine, would it be possible to reproduce the same tracer? 2. Find By car number plate
How i can make it? I only have 2 snipperS

Lua:
:SAMPGetCarNumberPlateByVehicleID

{
    0.3.7 - R5

    0AB1: @SAMPGetCarNumberPlateByVehicleID 1 VehicleID 1249 _Returned: NumberPlate 0@
}
IF 0AA2: 10@ = "samp.dll"
THEN
    10@ += 0x26EB94 // SAMP_INFO_OFFSET
    0A8D: 10@ readMem 10@ sz 4 vp 0
    10@ += 0x3DE // SAMP_PPOOLS_OFFSET
    0A8D: 10@ readMem 10@ sz 4 vp 0
    10@ += 0x0 // SAMP_PPOOL_VEHICLE_OFFSET
    0A8D: 10@ readMem 10@ sz 4 vp 0
    0@ *= 0x4 // VEHICLE_ID * 0x14
    0@ += 0x1134
    005A: 10@ += 0@
    0A8D: 10@ = readMem 10@ sz 4 vp 0
    10@ += 0x93 // SAMP_VEHICLE_NUMBER_PLATE_OFFSET
    0A8D: 4@ = readMem 10@ sz 1 vp 0
    IF 4@ > 0
    THEN 0485:  return_true
    ELSE
        059A:  return_false
        10@ = 0
    END
END
0AB2: ret 1 10@



Lua:
:SAMPGetVehicleIDbyCarHandle // if 0AB1: @SAMPGetVehicleIDbyCarHandle 1 _OfCarHandle 0@ _StoreVehicleID 29@
if 0AA2: 31@ = load_dynamic_library "samp.dll" // pSAMPBase // no need to Free Memory
then
    31@ += 0x26EB94
    0A8D: 31@ = read_memory 31@ size 4 virtual_protect 0 // stSAMPInfo
    if 31@ > 0
    then
        31@ += 0x3DE
        0A8D: 31@ = read_memory 31@ size 4 virtual_protect 0 // stSAMPPools
        if 31@ > 0
        then
            31@ += 0x0
            0A8D: 31@ = read_memory 31@ size 4 virtual_protect 0 // stVehiclePool
            if 31@ > 0
            then
                0A97: 30@ = vehicle 0@ struct
                for 29@ = 0 to 8000 step 4 // vehicle index = max vehicle * 4 = 2000 * 4
                    0A8E: 28@ = 29@ + 31@
                    0A8E: 27@ = 28@ + 0x3074
                    0A8D: 27@ = read_memory 27@ size 4 virtual_protect 0 // iIsListed
                    if 27@ > 0
                    then
                        0A8E: 27@ = 28@ + 0x1134
                        0A8D: 27@ = read_memory 27@ size 4 virtual_protect 0 // pSAMP_Vehicle
                        if 27@ > 0
                        then
                            27@ += 0x4C
                            0A8D: 26@ = read_memory 27@ size 4 virtual_protect 0 // pGTA_Vehicle
                            if 003B: 26@ == 30@  // our vehicle matched
                            then
                                29@ /= 4
                                0485:  return_true
                                ret 1 29@ // I now Got the Vehicle ID
                            end
                        end
                    end
                end
            end
        end
    end
end
059A:  return_false
ret 1 -1 // null Vehicle ID





Lua:
function FindVehicleByNumberPlate(targetNumberPlate)
    local sampDLL = loadLibrary("samp.dll")
    if sampDLL then
        local stSAMPInfo = readMemory(sampDLL + 0x26EB94, 4)
        if stSAMPInfo > 0 then
            local stSAMPPools = readMemory(stSAMPInfo + 0x3DE, 4)
            if stSAMPPools > 0 then
                local stVehiclePool = readMemory(stSAMPPools + 0x0, 4)
                if stVehiclePool > 0 then
                    for i = 0, 2000 do
                        local vehicleIndex = i * 4
                        local vehicleAddr = readMemory(stVehiclePool + vehicleIndex + 0x1134, 4)
                        if vehicleAddr > 0 then
                            local numberPlate = readMemory(vehicleAddr + 0x93, 1)
                            if numberPlate == targetNumberPlate then
                                return vehicleAddr
                            end
                        end
                    end
                end
            end
        end
    end
    return nil
end

function CreateTracerToVehicle(vehicleAddr)
    if vehicleAddr then
        local vehiclePosition = GetVehiclePosition(vehicleAddr)
        local playerPosition = GetPlayerPosition()
        if vehiclePosition and playerPosition then
            local direction = {
                x = vehiclePosition.x - playerPosition.x,
                y = vehiclePosition.y - playerPosition.y,
                z = vehiclePosition.z - playerPosition.z
            }

            local magnitude = math.sqrt(direction.x^2 + direction.y^2 + direction.z^2)
            direction.x = direction.x / magnitude
            direction.y = direction.y / magnitude
            direction.z = direction.z / magnitude

            RenderTracer(playerPosition, direction, "green", magnitude)
        end
    else
        print("Vehicle not found.")
    end
end

local numberPlateToFind = "ABC123"
local vehicleAddress = FindVehicleByNumberPlate(numberPlateToFind)

if vehicleAddress then
    CreateTracerToVehicle(vehicleAddress)
else
    print("Vehicle with number plate ".. numberPlateToFind .." not found.")
end
Lua:
        local font = renderCreateFont("Century Gothic", 12, 5)
        for k, v in pairs(getAllVehicles()) do
            local x, y, z = getCarCoordinates(v)
            local px, py, pz = getCharCoordinates(PLAYER_PED)
            if isPointOnScreen(x, y, z, 0.2) then
                if getDistanceBetweenCoords3d(x, y, z, px, py, pz) < 100 then
                    local tdPx, tdPy = convert3DCoordsToScreen(px, py, pz)
                    local tdX, tdY = convert3DCoordsToScreen(x, y, z)
                    local modelId = getCarModel(v)
                    local model = getNameOfVehicleModel(modelId)
                    if not isCharInCar(PLAYER_PED, v) then
                        renderFontDrawText(font, tostring(model), tdX, tdY, -1, false)
                        renderDrawLine(tdPx, tdPy, tdX, tdY, 1.0, 0xFF44944A)
                    end
                end
            end
        end
you can do this by get all vehicles coordinates and read the documentation, otherwise it seems from the code that chatgpt wrote it

Как можно выполнить функу при прыжке игрока?
Lua:
        if sampGetPlayerAnimationId(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))) == 1197 and act then
            act = false
            sampAddChatMessage('jump', -1)
            --your code
        elseif sampGetPlayerAnimationId(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))) == 1195 and not act then
            act = true
        end

Как после бега к 3д тексту сделать так что бы он останавливался на секунд 20, а после пошел на другой 3д текст
Lua:
local run = false

function runToPoint(tox, toy)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local angle = getHeadingFromVector2d(tox - x, toy - y)
    local xAngle = math.random(-50, 50)/100
    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
    stopRun = false
    while getDistanceBetweenCoords2d(x, y, tox, toy) > 0.8 do
        setGameKeyState(1, -255)
        --setGameKeyState(16, 1)
        wait(1)
        x, y, z = getCharCoordinates(PLAYER_PED)
        angle = getHeadingFromVector2d(tox - x, toy - y)
        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
        if stopRun then
            stopRun = false
            break
        end
    end
end

function main()
    repeat wait(0) until isSampAvailable()
        sampRegisterChatCommand('cmds',function()
            run = not run
            sampAddChatMessage('Состояние: ' ..(run and 'Вкл' or 'Выкл'),-1)
        end)

    while true do wait(0)
        if run then
            for i = 0,2048 do
                if sampIs3dTextDefined(i) then
                    text, clr, posX, posY, posZ, dist, wh, plid, vehid = sampGet3dTextInfoById(i)
                    if string.match(text,'урожая') then
                        runToPoint(posX,posY)
                        run = false
                    end
                end
            end
        end
    end
end

Lua:
local run = false

function runToPoint(tox, toy)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local angle = getHeadingFromVector2d(tox - x, toy - y)
    local xAngle = math.random(-50, 50)/100
    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
    stopRun = false
    while getDistanceBetweenCoords2d(x, y, tox, toy) > 0.8 do
        setGameKeyState(1, -255)
        --setGameKeyState(16, 1)
        wait(1)
        x, y, z = getCharCoordinates(PLAYER_PED)
        angle = getHeadingFromVector2d(tox - x, toy - y)
        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
        if stopRun then
            stopRun = false
            break
        end
    end
end

function main()
    repeat wait(0) until isSampAvailable()
        sampRegisterChatCommand('cmds',function()
            run = not run
            sampAddChatMessage('Состояние: ' ..(run and 'Вкл' or 'Выкл'),-1)
        end)

    while true do wait(0)
        if run then
            for i = 0,2048 do
                if sampIs3dTextDefined(i) then
                    text, clr, posX, posY, posZ, dist, wh, plid, vehid = sampGet3dTextInfoById(i)
                    if string.match(text,'урожая') then
                        runToPoint(posX,posY)
                        run = false
                        wait(20000) -- время в мс
                        run = true
                    end
                end
            end
        end
    end
end
ну судя по твоему коду, через 20 секунд я просто переключаю run на true
 
Последнее редактирование:

uvie

Известный
271
54
Lua:
        local font = renderCreateFont("Century Gothic", 12, 5)
        for k, v in pairs(getAllVehicles()) do
            local x, y, z = getCarCoordinates(v)
            local px, py, pz = getCharCoordinates(PLAYER_PED)
            if isPointOnScreen(x, y, z, 0.2) then
                if getDistanceBetweenCoords3d(x, y, z, px, py, pz) < 100 then
                    local tdPx, tdPy = convert3DCoordsToScreen(px, py, pz)
                    local tdX, tdY = convert3DCoordsToScreen(x, y, z)
                    local modelId = getCarModel(v)
                    local model = getNameOfVehicleModel(modelId)
                    if not isCharInCar(PLAYER_PED, v) then
                        renderFontDrawText(font, tostring(model), tdX, tdY, -1, false)
                        renderDrawLine(tdPx, tdPy, tdX, tdY, 1.0, 0xFF44944A)
                    end
                end
            end
        end
you can do this by get all vehicles coordinates and read the documentation, otherwise it seems from the code that chatgpt wrote it


Lua:
        if sampGetPlayerAnimationId(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))) == 1197 and act then
            act = false
            sampleAddChatMessage('jump', -1)
            --your code
        elseif sampGetPlayerAnimationId(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))) == 1195 and not act then
            act = true
        end



Lua:
local run = false

function runToPoint(tox, toy)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local angle = getHeadingFromVector2d(tox - x, toy - y)
    local xAngle = math.random(-50, 50)/100
    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
    stopRun = false
    while getDistanceBetweenCoords2d(x, y, tox, toy) > 0.8 do
        setGameKeyState(1, -255)
        --setGameKeyState(16, 1)
        wait(1)
        x, y, z = getCharCoordinates(PLAYER_PED)
        angle = getHeadingFromVector2d(tox - x, toy - y)
        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
        if stopRun then
            stopRun = false
            break
        end
    end
end

function main()
    repeat wait(0) until isSampAvailable()
        sampRegisterChatCommand('cmds',function()
            run = not run
            sampAddChatMessage('State: ' ..(run and 'On' or 'Off'),-1)
        end)

    while true do wait(0)
        if run then
            for i = 0,2048 do
                if sampIs3dTextDefined(i) then
                    text, clr, posX, posY, posZ, dist, wh, plid, vehid = sampGet3dTextInfoById(i)
                    if string.match(text,'урожая') then
                        runToPoint(posX,posY)
                        run = false
                        wait(20000) -- time in ms
                        run = true
                    end
                end
            end
        end
    end
end
Well, judging by your code, after 20 seconds I just switch run to true
I'm playing on R5 version SAMP so all my LUAS are on R5 here what other dev lua sent mel

Lua:
local FONT = nil
local STATE = true

function main()
    if not (sampRegisterChatCommand and renderCreateFont and getAllVehicles) then
        return
    end

    FONT = renderCreateFont('Arial', 9, 4)

    sampRegisterChatCommand('vagis', function()
        STATE = not STATE
        if sampAddChatMessage then
            sampAddChatMessage(string.format('{696969}[vagis]:{FFFFFF} %s', STATE and 'Enabled' or 'Disabled'), -1)
        end
    end)
    
    while true do
        wait(0)
        if STATE then
            for _, handle in pairs(getAllVehicles()) do
                local result, vehicleId = sampGetVehicleIdByCarHandle(handle)
                if result then
                    local PLAYER_POS = {getCharCoordinates(PLAYER_PED)}
                    local CAR_POS = {getCarCoordinates(handle)}
                    if isPointOnScreen(CAR_POS[1], CAR_POS[2], CAR_POS[3], 2) then
                        local DISTANCE = getDistanceBetweenCoords3d(CAR_POS[1], CAR_POS[2], CAR_POS[3], PLAYER_POS[1], PLAYER_POS[2], PLAYER_POS[3])
                        local sX, sY = convert3DCoordsToScreen(CAR_POS[1], CAR_POS[2], CAR_POS[3])
                        local asX, asY = convert3DCoordsToScreen(PLAYER_POS[1], PLAYER_POS[2], PLAYER_POS[3])
                        local modelName = getNameOfVehicleModel(getCarModel(handle)) or 'Unknown Model'
                        renderDrawLine(sX, sY, asX, asY, 2, 0xC000FF00)
                        renderDrawPolygon(sX, sY, 6, 6, 6, 0, 0xC000FF00)
                        renderFontDrawText(FONT, modelName, sX, sY - 20, 0x80FFFFFF)
                    end
                end
            end
        end
    end
end


also this is my friend sent me
According to the veh handle, you get the veh id
According to that idea, you get the numbers
Compare to null value
And put the name of the machine
 

fokichevskiy

Известный
461
237
I'm playing on R5 version SAMP so all my LUAS are on R5 here what other lua dev sent me


Код:
local FONT = nil
local STATE = true

function main()
    if not (sampRegisterChatCommand and renderCreateFont and getAllVehicles) then
        return
    end

    FONT = renderCreateFont('Arial', 9, 4)

    sampRegisterChatCommand('vagis', function()
        STATE = not STATE
        if sampAddChatMessage then
            sampAddChatMessage(string.format('{696969}[vagis]:{FFFFFF} %s', STATE and 'Enabled' or 'Disabled'), -1)
        end
    end)
  
    while true do
        wait(0)
        if STATE then
            for _, handle in pairs(getAllVehicles()) do
                local result, vehicleId = sampGetVehicleIdByCarHandle(handle)
                if result then
                    local PLAYER_POS = {getCharCoordinates(PLAYER_PED)}
                    local CAR_POS = {getCarCoordinates(handle)}
                    if isPointOnScreen(CAR_POS[1], CAR_POS[2], CAR_POS[3], 2) then
                        local DISTANCE = getDistanceBetweenCoords3d(CAR_POS[1], CAR_POS[2], CAR_POS[3], PLAYER_POS[1], PLAYER_POS[2], PLAYER_POS[3])
                        local sX, sY = convert3DCoordsToScreen(CAR_POS[1], CAR_POS[2], CAR_POS[3])
                        local asX, asY = convert3DCoordsToScreen(PLAYER_POS[1], PLAYER_POS[2], PLAYER_POS[3])
                        local modelName = getNameOfVehicleModel(getCarModel(handle)) or 'Unknown Model'
                        renderDrawLine(sX, sY, asX, asY, 2, 0xC000FF00)
                        renderDrawPolygon(sX, sY, 6, 6, 6, 0, 0xC000FF00)
                        renderFontDrawText(FONT, modelName, sX, sY - 20, 0x80FFFFFF)
                    end
                end
            end
        end
    end
end





According to the veh handle, you get the veh id
According to that idea, you get the numbers
Compare to null value
And put the name of the machine

the method is the same

1722428242678.png
 

Klimer

Активный
161
44
Как сделать так что бы скрипт не ходил к определенному 3д тексту - (Для новичков) и что бы после wait нажимало Alt а после нажимал лкм 6 раз с таймингом по 500 мс
Lua:
local run = false

function runToPoint(tox, toy)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local angle = getHeadingFromVector2d(tox - x, toy - y)
    local xAngle = math.random(-50, 50)/100
    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
    stopRun = false
    while getDistanceBetweenCoords2d(x, y, tox, toy) > 0.8 do
        setGameKeyState(1, -255)
        --setGameKeyState(16, 1)
        wait(1)
        x, y, z = getCharCoordinates(PLAYER_PED)
        angle = getHeadingFromVector2d(tox - x, toy - y)
        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
        if stopRun then
            stopRun = false
            break
        end
    end
end

function main()
    repeat wait(0) until isSampAvailable()
        sampRegisterChatCommand('timur',function()
            run = not run
            sampAddChatMessage('Состояние: ' ..(run and 'Вкл' or 'Выкл'),-1)
        end)

    while true do wait(0)
        if run then
            for i = 0,2048 do
                if sampIs3dTextDefined(i) then
                    text, clr, posX, posY, posZ, dist, wh, plid, vehid = sampGet3dTextInfoById(i)
                    if string.match(text,'урожая') then
                        runToPoint(posX,posY)
                        run = false
                        wait(20000) -- время в мс
                        run = true
                    end
                end
            end
        end
    end
end
 
Последнее редактирование:

Klimer

Активный
161
44
всем привет столкнулся с такой проблемой, персонаж идет к 3д тексту, но на сервере имеется идентичный куст на ферме только у него написанно (Для новичков)


Lua:
script_author("L1ct0r")
script_name("Cotton Bot v1.64")

local sampev = require 'lib.samp.events'
local inicfg = require 'inicfg'
local hook = require 'lib.samp.events'
local key = require 'vkeys'
local imgui = require 'imgui'

local encoding = require 'encoding'
encoding.default = 'CP1251'
local u8 = encoding.UTF8
local found,finding,active,pricesetup,collectcash,runtoc,slap = false,false,false,false,false,false,false
local ax,ay,tid,fx,fy,timer,totalLn,totalCtn,nextmatch,startime,countime = 0,0,0,0,0,0,0,0,1,os.time(),os.time()

local emx,emy = -257,-1362
local matches,fmatches,calcf = {},{},{}
local spx,spy = math.random(-1,1),math.random(-1,1)

local mainIni = inicfg.load({
    prices = {
        cotton = 526,
        len = 652
    }
})

local font_flag = require('moonloader').font_flag
local my_font = renderCreateFont('Verdana', 12, font_flag.BOLD + font_flag.SHADOW)

local priceCotton = mainIni.prices.cotton
local priceLen = mainIni.prices.len

local show_main_window,show_stats,jump_walk,go_free,get_cash = imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false)
local jump_run,clctln,clctctn = imgui.ImBool(true),imgui.ImBool(true),imgui.ImBool(true)
local lap = imgui.ImInt(0)

function SecondsToClock(seconds)
    local seconds = tonumber(seconds)
    if seconds <= 0 then
        return "00:00:00";
    else
        hours = string.format("%02.f", math.floor(seconds/3600));
        mins = string.format("%02.f", math.floor(seconds/60 - (hours*60)));
        secs = string.format("%02.f", math.floor(seconds - hours*3600 - mins *60));
        return hours..":"..mins..":"..secs
    end
end

function imgui.OnDrawFrame()
    if show_main_window.v then
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sw/2, sh/2), imgui.Cond.FirstUseEver)
        imgui.Begin(u8'Настройки бота хлопка/льна', show_main_window)
        imgui.ShowCursor = true
        if imgui.Checkbox(u8"Бежать прыгая", jump_run) then jump_walk.v = false end
        if imgui.Checkbox(u8"Идти прыгая", jump_walk) then jump_run.v = false end
        imgui.Checkbox(u8"Собирать лён", clctln)
        imgui.Checkbox(u8"Собирать хлопок", clctctn)
        imgui.Checkbox(u8"Идти на самый не занятый куст", go_free)
        imgui.Checkbox(u8"Продать ресурсы после кругов", get_cash)
        imgui.Checkbox(u8"Показывать статистику", show_stats)
        imgui.SliderInt(u8'Кол-во кругов', lap, 1, 2000, "%.0f")
        imgui.End()
    end
    if show_stats.v then
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2 - sw / 2.75, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sw/7, sh/4), imgui.Cond.FirstUseEver)
        imgui.Begin(u8'Статистика', show_stats)
        imgui.Text(u8'Бот работает: '..SecondsToClock(countime - startime))
        imgui.Text(u8'Собрано льна: '..totalLn)
        imgui.Text(u8'Собрано хлопка: '..totalCtn)
        imgui.Text(u8'Прибыль с льна: $'..totalLn*priceLen)
        imgui.Text(u8'Прибыль с хлопка: $'..totalCtn*priceCotton)
        imgui.Text(u8'Общая прибыль: $'..(totalLn*priceLen)+(totalCtn*priceCotton))
        if imgui.Button(u8"Очистить статистику") then
            totalLn,totalCtn,countime,startime = 0,0,os.time(),os.time()
        end
        imgui.End()
    end
end

function mode(arg)
    active = not active
    if active then
        sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Бот включен!",-1)
        startime = os.time()
    else
        sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Бот выключен!",-1)
    end
end

function showupmenu(arg)
    show_main_window.v = not show_main_window.v
end

function GetNearestCoord(Array)
    local x, y = getCharCoordinates(PLAYER_PED)
    local distance = {}
    for k, v in pairs(Array) do
        distance[k] = {distance = math.floor(getDistanceBetweenCoords2d(v[1], v[2], x, y)), id = v[3], name = v[4], vx=v[1],vy=v[2],cas=v[5]}
    end
    table.sort(distance, function(a, b) return a.distance < b.distance end)
    if go_free.v then table.sort(distance, function(a, b) if a.cas ~= nil or b.cas ~= nil then return a.cas < b.cas end end) end
    if #distance ~= 0 then
        local n = distance[1]
        local id = n.id
        local name = n.name
        return n.vx,n.vy,id,name
    end
end

function setCameraPos(a, b)
    local z = b[1] - a[1]
    local camZ = math.atan((b[2] - a[2]) / z)
    if z >= 0.0 then
        camZ = camZ + 3.14
    end
    setCameraPositionUnfixed(0.0, camZ)
end

function runTo(bx,by,cx,cy,dist)
    setCameraPos({bx,by},{cx+spx,cy+spy})
    setGameKeyState(1,-256)
    local def = dist/10
    if jump_run.v then
        if dist > 3 then
            timer = timer + 1
            if timer > 135 then
                setGameKeyState(14,-256)
                timer = 0
                spx,spy = math.random(-1+def,1-def),math.random(-1+def,1-def)
            else
                setGameKeyState(14,0)
                setGameKeyState(16,-256)
            end
        else
            setGameKeyState(16,-256)
        end
    else
        setGameKeyState(16,-256)
    end
end

function hook.onDisplayGameText(style,tm,text)
    if text == "linen + 1" then
        totalLn = totalLn + 1
    elseif text == "cotton + 1" then
        totalCtn = totalCtn + 1
    end
end

function hook.onSendPlayerSync()
    if slap then
        return false
    end
end

function hook.onSetPlayerPos(pos)
    if active and found and not slap then
        slap = true
        sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Кажется админ спалил бота! Уходим в фейк афк на минуту.",-1)
    end
end

function main()
    while not isSampAvailable() do wait(0) end
    sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Бот на добычу хлопка/льна успешно загрузился!",-1)
    sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Скрипт сделан для BlastHack",-1)
    sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Автор: {30F867}Lackter",-1)
    sampRegisterChatCommand("botc", mode)
    sampRegisterChatCommand("botcmenu", showupmenu)
    if not mainIni.prices then inicfg.save(mainIni) end
    if slap then
        wait(60000)
        slap = false
    end
    while true do
        wait(0)
        if sampGetCurrentDialogId() == 8413 and not pricesetup then
            local i = 0
            for pr in string.gmatch(sampGetDialogText(), "$%d+") do
                if i == 0 then
                    priceCotton = tonumber(pr:sub(2,pr:len()))
                    mainIni.prices.cotton = priceCotton
                elseif i == 1 then
                    priceLen = tonumber(pr:sub(2,pr:len()))
                    mainIni.prices.len = priceLen
                else
                    inicfg.save(mainIni)
                end
                i=i+1
            end
            
            pricesetup = true
        elseif sampGetCurrentDialogId() == 8413 and collectcash then
            local i = 0
            local hasLen,hasCotton = 0,0
            for pr in string.gmatch(sampGetDialogText(), "%d+ шт") do
                if i == 0 then
                    hasCotton=tonumber(pr:sub(1,pr:len()-3))
                elseif i == 1 then
                    hasLen=tonumber(pr:sub(1,pr:len()-3))
                end
                i=i+1
            end
            if hasLen ~= 0 then
                sampSendDialogResponse(8413, 1, 1, "")
                sampSendDialogResponse(8414, 1, 1, tostring(hasLen))
            end
            if hasCotton ~= 0 then
                sampSendDialogResponse(8413, 1, 1, "")
                sampSendDialogResponse(8414, 1, 1, tostring(hasCotton))
            end
            collectcash = false
        end
        
        imgui.Process = show_main_window.v
        if not show_main_window.v and show_stats.v then
            imgui.Process = show_stats.v
            imgui.ShowCursor = false
        end
        if active then
            countime = os.time()
        end
        if runtoc then
            local x,y = getCharCoordinates(PLAYER_PED)
            local dis = getDistanceBetweenCoords2d(x, y, emx, emy)
            if dis > 2 then
                runTo(x,y,emx,emy,dis)
            else
                setGameKeyState(21,-256)
                collectcash = true
            end
        end
        local res, pid = sampGetPlayerIdByCharHandle(PLAYER_PED)
        if not found and active and lap.v ~= 0 then
            local dp = {}
            local cdp = {}
            local dpd = false
            for id = 0, 2048 do
                local result = sampIs3dTextDefined(id)
                if result then
                    local text, color, posX, posY = sampGet3dTextInfoById( id )
                    if string.match(text,"урожая",0) then
                        local d = ""
                        if text:find("Хлопок") then
                            d = "Хлопок"
                            if clctctn.v then
                                local countplys = 0
                                if go_free.v then
                                    for _,v in pairs(getAllChars()) do
                                        if v ~= PLAYER_PED then
                                            local x,y,z = getCharCoordinates(v)
                                            if getDistanceBetweenCoords2d(x, y, posX, posY) < 2 then
                                                countplys=countplys+1
                                            end
                                        end
                                    end
                                end
                                table.insert(matches,{posX,posY,id,d,countplys})
                            end
                        elseif text:find("Лён") then
                            d = "Лён"
                            if clctln.v then
                                local countplys = 0
                                if go_free.v then
                                    for _,v in pairs(getAllChars()) do
                                        if v ~= PLAYER_PED then
                                            local x,y,z = getCharCoordinates(v)
                                            if getDistanceBetweenCoords2d(x, y, posX, posY) < 2 then
                                                countplys=countplys+1
                                            end
                                        end
                                    end
                                end
                                table.insert(matches,{posX,posY,id,d,countplys})
                            end
                        end
                    elseif string.match(text,"Осталось 0:0%d+",0) then
                        table.insert(fmatches,{posX,posY,123,"123"})
                    end
                end
            end
            if #matches ~= 0 then
                local lx,ly,id,name = GetNearestCoord(matches)
                found = true
                finding = false
                ax,ay = lx,ly
                tid = id
                if name ~= "" then sampAddChatMessage("{30F867}[ARZ]{FFFFFF} ".. name .." найден! Идем к нему!",-1) end
            end
            if #fmatches ~= 0 and not found then
                local lx,ly,id,name = GetNearestCoord(fmatches)
                finding = true
                fx,fy = lx,ly
            end
        end
        if not found and finding and active then
            local x,y = getCharCoordinates(PLAYER_PED)
            local dis = getDistanceBetweenCoords2d(x, y, fx, fy)
            if dis > 6 then
                runTo(x,y,fx,fy,dis)
            else
                finding = false
                fmatches = {}
            end
            
        end
        if found and active then
            local anim = sampGetPlayerAnimationId(pid)
            local x,y = getCharCoordinates(PLAYER_PED)
            local dis = getDistanceBetweenCoords2d(x, y, ax, ay)
            if dis > 250 then
                script:reload()
            end
            if dis > 2 then
                runTo(x,y,ax,ay,dis)
                local text = sampGet3dTextInfoById( tid )
                if text == "" then found = false timer = 0 ax = 0 ay = 0 tid = 0 end
            else
                setGameKeyState(1,0)
                local text = sampGet3dTextInfoById( tid )
                if string.match(text,"урожая",0) then
                    if anim == 168 then
                        setGameKeyState(21,-256)
                    else
                        if anim == 1189 then
                            setGameKeyState(21,0)
                            wait(250)
                            setGameKeyState(21,-256)
                            temp = 1
                        else
                            setGameKeyState(21,-256)
                        end
                    end
                else
                    wait(25)
                    found = false
                    timer = 0
                    lap.v = lap.v - 1
                    matches = {}
                    if lap.v ~= 0 then sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Осталось ещё кругов: "..lap.v.."!",-255) elseif lap.v == 0 then sampAddChatMessage("{30F867}[ARZ]{FFFFFF} Круги закончились!",-255) if get_cash.v then runtoc = true end end
                end
            end
        end
    end
end
 

kuboni

Потрачен
154
2
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
onshowtextdraw
If id 2054 to 2074 have the same data.letterColor, then ignore the differences and then accept. Is there any way to make the code work smoothly?
 

Tr1x2er

Участник
102
10
1. Помогите, как правильно достать никнеймы игроков для логов скрипта?
они неправильно отображаются

2. Как сделать так, чтобы скрипт реагировал на конкретное слово и исключал те случаи, когда это слово находится в неизвестном предложении?