Полезные сниппеты и функции

Albertio

Attention! Thanks for your attention.
878
701
Описание: Получает серверный id ближайшей машины
Lua:
function getClosestCarId()
  local minDist = 9999
  local closestId = -1
  local x, y, z = getCharCoordinates(PLAYER_PED)
  for i, k in ipairs(getAllVehicles()) do
    local streamed, carId = sampGetVehicleIdByCarHandle(k)
    if streamed then
      local xi, yi, zi = getCarCoordinates(k)
      local dist = math.sqrt( (xi - x) ^ 2 + (yi - y) ^ 2 + (zi - z) ^ 2 )
      if dist < minDist then
        minDist = dist
        closestId = carId
      end
    end
  end
  return closestId
end
Пример использования:
Lua:
function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("carid", function()
        sampAddChatMessage("Самая ближайшая машина к вам имеет ID: "..getClosestCarId(), -1)
    end)
  while true do
    wait(0)
  end
end

function getClosestCarId()
  local minDist = 9999
  local closestId = -1
  local x, y, z = getCharCoordinates(PLAYER_PED)
  for i, k in ipairs(getAllVehicles()) do
    local streamed, carId = sampGetVehicleIdByCarHandle(k)
    if streamed then
      local xi, yi, zi = getCarCoordinates(k)
      local dist = math.sqrt( (xi - x) ^ 2 + (yi - y) ^ 2 + (zi - z) ^ 2 )
      if dist < minDist then
        minDist = dist
        closestId = carId
      end
    end
  end
  return closestId
end
 
Последнее редактирование:

imring

Ride the Lightning
Всефорумный модератор
2,353
2,512
Описание: Получает серверный id ближайшей машины
Lua:
function getClosestCarId()
  local minDist = 9999
  local closestId = -1
  local x, y, z = getCharCoordinates(PLAYER_PED)
  for i = 0, 1800 do
    local streamed, pedID = sampGetCarHandleBySampVehicleId(i)
    if streamed then
      local xi, yi, zi = getCarCoordinates(pedID)
      local dist = math.sqrt( (xi - x) ^ 2 + (yi - y) ^ 2 + (zi - z) ^ 2 )
      if dist < minDist then
        minDist = dist
        closestId = i
      end
    end
  end
  return closestId
end
Пример использования:
Lua:
function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("carid", function()
        sampAddChatMessage("Самая ближайшая машина к вам имеет ID: "..getClosestCarId(), -1)
    end)
  while true do
    wait(0)
  end
end

function getClosestCarId()
  local minDist = 9999
  local closestId = -1
  local x, y, z = getCharCoordinates(PLAYER_PED)
  for i = 0, 1800 do
    local streamed, pedID = sampGetCarHandleBySampVehicleId(i)
    if streamed then
      local xi, yi, zi = getCarCoordinates(pedID)
      local dist = math.sqrt( (xi - x) ^ 2 + (yi - y) ^ 2 + (zi - z) ^ 2 )
      if dist < minDist then
        minDist = dist
        closestId = i
      end
    end
  end
  return closestId
end
Lua:
local veh = storeClosestEntities(playerPed)
if doesVehicleExist(veh) then
    local res, id = sampGetVehicleIdByCarHandle(veh)
end
или можно было-бы чекнуть все машини с помощью getAllVehicles
 

Cosmo

Известный
Друг
644
2,581
Описание:
Кликабельная ссылка
Lua:
function imgui.Link(link, text)
    text = text or link
    local tSize = imgui.CalcTextSize(text)
    local p = imgui.GetCursorScreenPos()
    local DL = imgui.GetWindowDrawList()
    local col = { 0xFFFF7700, 0xFFFF9900 }
    if imgui.InvisibleButton("##" .. link, tSize) then os.execute("explorer " .. link) end
    local color = imgui.IsItemHovered() and col[1] or col[2]
    DL:AddText(p, color, text)
    DL:AddLine(imgui.ImVec2(p.x, p.y + tSize.y), imgui.ImVec2(p.x + tSize.x, p.y + tSize.y), color)
end

Пример использования:
Lua:
imgui.Text(u8"Лучший форум на свете:")
imgui.SameLine()
imgui.Link("https://www.blast.hk/")

link.gif
 
Последнее редактирование:

Quasper

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

Описание: Генератор символов из заданного шаблона
Lua:
function generator(str, len)
    local str_ = ""
    math.randomseed(os.time(), math.random(os.time(), os.clock()))
    for i = 1, len do
      local index = math.random(1, #str)
      str_ = str_ .. str:sub(index, index)
    end
    return str_
end
Пример использования:
Lua:
generator("AaBbCcDdEe123456", 10) -- Вернёт случайно сгенерированную строку из этого шаблона размером в 10 символов
 
  • Нравится
Реакции: HpP и Cosmo

neverlane

t.me/neverlane00
Друг
998
1,141
Описание: добавляет в imgui круглую кнопку которую можно настроить
Lua:
function imgui.RoundButton(str_id, radius, round_float)
    radius = radius or 10
    round_float = round_float or 8.0
    imgui.PushStyleVar(imgui.StyleVar.FrameRounding, round_float)
    local roundbtnres = imgui.Button(str_id,imgui.ImVec2(radius*2,radius*2))
    imgui.PopStyleVar(1)
    return roundbtnres
end
Пример использования:
Lua:
--1 аргумент - название
--2 аргумент - радиус, если не указать то будет = 10
--3 аргумент - закругление, если не указать то будет = 8.0
if imgui.RoundButton('+',15,16.0) then
    sampAddChatMessage('Round',-1)
end
imgui.RoundButton('-',15,16.0)
SoaMtJB.png
 

#Northn

Police Helper «Reborn» — уже ШЕСТЬ лет!
Всефорумный модератор
2,633
2,479
Описание: Получение текущего FPS. Да да, костыльно, но ни один другой способ не выводит реальное кол-во.
Lua:
local fps = 0
local fps_counter = 0

lua_thread.create(function()
    while true do
        wait(1000)
        fps = fps_counter
        fps_counter = 0
    end
end)

function onD3DPresent()
    fps_counter = fps_counter + 1
end

Пример использования:
Lua:
    sampRegisterChatCommand("fps",function()
        sampAddChatMessage("Кол-во FPS: "..fps,-1)
    end)
Lua:
local ffi = require 'ffi'

local fps = {
    last_update = 0,
    value = 0,
    get = function()
        if os.clock() - fps.last_update > 1.2 then
                fps.last_update = os.clock(),
                fps.value = math.ceil(ffi.cast('float*', 0xB7CB50)[0])
        end
        return fps.value
    end
}
 
Последнее редактирование:

neverlane

t.me/neverlane00
Друг
998
1,141
Описание: Кликабельная ссылка
Lua:
function imgui.Link(link)
    if status_hovered then
        local p = imgui.GetCursorScreenPos()
        imgui.TextColored(imgui.ImVec4(0, 0.5, 1, 1), link)
        imgui.GetWindowDrawList():AddLine(imgui.ImVec2(p.x, p.y + imgui.CalcTextSize(link).y), imgui.ImVec2(p.x + imgui.CalcTextSize(link).x, p.y + imgui.CalcTextSize(link).y), imgui.GetColorU32(imgui.ImVec4(0, 0.5, 1, 1)))
    else
        imgui.TextColored(imgui.ImVec4(0, 0.3, 0.8, 1), link)
    end
    if imgui.IsItemClicked() then os.execute('explorer '..link)
    elseif imgui.IsItemHovered() then
        status_hovered = true else status_hovered = false
    end
end
Пример использования:
Lua:
imgui.Link("https://www.blast.hk/")

Посмотреть вложение 58541
Обновлю функцию от @Cosmo
Описание: Кликабельная ссылка v2(самое главное что можно делать несколько гиперссылок)
Lua:
function imgui.Link(link,name,myfunc)
    myfunc = type(name) == 'boolean' and name or myfunc or false
    name = type(name) == 'string' and name or type(name) == 'boolean' and link or link
    local size = imgui.CalcTextSize(name)
    local p = imgui.GetCursorScreenPos()
    local p2 = imgui.GetCursorPos()
    local resultBtn = imgui.InvisibleButton('##'..link..name, size)
    if resultBtn then
        if not myfunc then
            os.execute('explorer '..link)
        end
    end
    imgui.SetCursorPos(p2)
    if imgui.IsItemHovered() then
        imgui.TextColored(imgui.ImVec4(0, 0.5, 1, 1), name)
        imgui.GetWindowDrawList():AddLine(imgui.ImVec2(p.x, p.y + size.y), imgui.ImVec2(p.x + size.x, p.y + size.y), imgui.GetColorU32(imgui.ImVec4(0, 0.5, 1, 1)))
    else
        imgui.TextColored(imgui.ImVec4(0, 0.3, 0.8, 1), name)
    end
    return resultBtn
end
Lua:
function imgui.Link(link,name,myfunc)
    myfunc = type(name) == 'boolean' and name or myfunc or false
    name = type(name) == 'string' and name or type(name) == 'boolean' and link or link
    local size = imgui.CalcTextSize(name)
    local p = imgui.GetCursorScreenPos()
    local p2 = imgui.GetCursorPos()
    local resultBtn = imgui.InvisibleButton('##'..link..name, size)
    if resultBtn then
        if not myfunc then
            os.execute('explorer '..link)
        end
    end
    imgui.SetCursorPos(p2)
    if imgui.IsItemHovered() then
        imgui.TextColored(imgui.GetStyle().Colors[imgui.Col.ButtonHovered], name)
        imgui.GetWindowDrawList():AddLine(imgui.ImVec2(p.x, p.y + size.y), imgui.ImVec2(p.x + size.x, p.y + size.y), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.ButtonHovered]))
    else
        imgui.TextColored(imgui.GetStyle().Colors[imgui.Col.Button], name)
    end
    return resultBtn
end

Пример использования:
Lua:
imgui.Link('https://vk.com') -- просто откроет ссылку, имя гиперссылки будет https://vk.com
imgui.Link('https://vk.com','VK') -- просто откроет ссылку, имя гиперссылки будет VK
if imgui.Link('https://vk.com','VK',true) then -- выполнит функцию ниже, имя гиперссылки будет VK
    sampAddChatMessage('test',-1)
end
if imgui.Link('https://vk.com',true) then -- выполнит функцию ниже, имя гиперссылки будет https://vk.com
    sampAddChatMessage('test',-1)
end
 
Последнее редактирование:

Albertio

Attention! Thanks for your attention.
878
701
Описание: Проверка на сворачивание/разворачивание окна игры
Lua:
local wm = require('lib.windows.message')

function onWindowMessage(msg, wparam, lparam)
  if msg == wm.WM_KILLFOCUS then
    --когда сворачиваешь игру
  elseif msg == wm.WM_SETFOCUS then
    --когда разворачиваешь игру
  end
end
Пример использования:
Lua:
local wm = require('lib.windows.message')

function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
  sampAddChatMessage("Пример проверки на сворачивание/разворачивание окна игры", - 1)
  while true do
    wait(0)
  end
end

function onWindowMessage(msg, wparam, lparam)
  if msg == wm.WM_KILLFOCUS then
    print("Вы свернули окно игры")
  elseif msg == wm.WM_SETFOCUS then
    print("Вы развернули окно игры")
  end
end
 

Quasper

Известный
834
354
Получить гендерную принадлежность по скину:
Lua:
function getGenderBySkinId(skinId)
local skins = {male = {0, 1, 2, 3, 4, 5, 6, 7, 8, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 66, 67, 68, 70, 71, 72, 73, 78, 79, 80, 81, 82, 83, 84, 86, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 132, 133, 134, 135, 136, 137, 142, 143, 144, 146, 147, 149, 153, 154, 155, 156, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 170, 171, 173, 174, 175, 176, 177, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 200, 202, 203, 204, 206, 208, 209, 210, 212, 213, 217, 220, 221, 222, 223, 227, 228, 229, 230, 234, 235, 236, 239, 240, 241, 242, 247, 248, 249, 250, 252, 253, 254, 255, 258, 259, 260, 261, 262, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 299, 300, 301, 302, 303, 304, 305, 310, 311}, 
female = {9, 10, 11, 12, 13, 31, 38, 39, 40, 41, 53, 54, 55, 56, 63, 64, 65, 69, 75, 76, 77, 85, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 139, 140, 141, 145, 148, 150, 151, 152, 157, 169, 172, 178, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 201, 205, 207, 211, 214, 215, 216, 218, 219, 224, 225, 226, 231, 232, 233, 237, 238, 243, 244, 245, 246, 251, 256, 257, 263, 298, 306, 307, 308, 309}}
for k, v in pairs(skins) do
  for m, n in pairs(v) do
      if n == skinId then
        return k
      end
  end
end
  return 'Skin not found'
end
Пример использования:
Lua:
print(getGenderBySkinId(0)) -- male
print(getGenderBySkinId(231)) -- female
print(getGenderBySkinId(315)) -- Skin not found
 

|DEVIL|

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

Требования: Асинхронные запросы и все зависимости связанные с ними, функцию по ссылке достаточно скопировать в свой код в самый низ. В настройках вашего сообщества должны быть включены уведомления от ботов и так же должен быть сгенерирован API токен с разрешением отправлять сообщения.

Важно: 1. ВК блокирует повторяющиеся сообщения, поэтому обязательно поставьте какой-нибудь счётчик сообщений или что-то другое что не будет повторяться. 2. Нужен именно айди человека и айди беседы, а не его короткий домен 3. Каждое сообщение кодируем в UTF-8 (В примере показано)

Функция:
Lua:
function VKMessage(userId, groupId, message, token)
    lua_thread.create(function()
    message = message:gsub(' ','%20')
    message = message:gsub('\n', '%0A')
    --За 2 строки выше спасибо человеку под ником CaJlaT
    httpRequest('https://api.vk.com/method/messages.send?user_id='..userId..'&random_id=0&peer_id='..groupId..'&message='..message..'&group_id='..groupId..'&access_token='..token..'&v=5.120')
    end)
    return true
end

Пример использования:
Lua:
local copas = require 'copas'
local http = require 'copas.http'
--Выше все зависимости функции

function main()
    sampRegisterChatCommand("test", test)
end

function test()
    VKMessage(356197383, 191433791, u8"Привет, а вот и я\nНовая строка", "d7297e17e8573ebb3fe9e5ef124b91c9067c0f020fc32b4d46ad2cfcfddf10dc102c778a073ec75a110b2")
end
--Токен не работает

1594138221597.png
 
Последнее редактирование:

trefa

Известный
Всефорумный модератор
2,095
1,225
Описание: Возвращает номер текущей недели в году (В первую и в последнюю неделю могут быть неточности)
Код немного подправлен @imring
Lua:
function number_week()
    local current_time = os.date'*t'
    local start_year = os.time{ year = current_time.year, day = 1, month = 1 }
    local week_day = ( os.date('%w', start_year) - 1 ) % 7 -- [0-6, Monday-Sunday]
    return math.ceil((current_time.yday + week_day) / 7)
end
Пример использования:
Lua:
print(number_week())
-- 28
 
Последнее редактирование:

donaks.

Активный
101
67
Описание: Вычисляет направление движения (север, юг, восток, запад) любого объекта по двум координатам и задержкой между ним в миллесекундах. Код написан человеком, который не шарит в ваших арктангенсах и азимутах и построен чисто на логике и знаний систем координат. Возвращает строку с направлением либо то, что объект стоит на месте. Если убрать else, то не будет ничего возвращать, когда объект стоит на месте.
Lua:
function getDirection(Xstart, Ystart, Xend, Yend, wait)
    -- Xstart, Ystart - стартовые координаты; Xend, Yend - финишные.
    -- wait - время прохождения этих координат объектом в миллисекундах.
    -- По умолчанию wait = 100

    if not wait or not type(wait) == 'number' then
        wait = 100
    end
    wait = wait / 100 -- 100 мс. - идеальная задержка для нижестоящих коэффициентов

    local d = {} -- direction
    d.x = Xend - Xstart
    d.y = Yend - Ystart

    -- переводим в модуль числа, чтобы вычислить "доминирующую сторону света"
    d.diff = math.abs(d.x) - math.abs(d.y)

    -- коэффициенты множим на "лишнюю" задержку
    if d.diff > (1.3 * wait) then
        return (d.x > 0 and "восточное" or "западное")
    elseif d.diff < (-1.3 * wait) then
        return (d.y > 0 and "северное" or "южное")
    elseif (d.x > (0.5 * wait) or d.x < (-0.5 * wait)) or (d.y > (0.5 * wait) or d.y < (-0.5 * wait)) then
        return (d.y > 0 and "северо" or "юго").."-"..(d.x > 0 and "восточное" or "западное")
    else
        return "стоит на месте"
    end
end
Пример использования:
Lua:
-- После написания команды, каждые waitms миллисекунд (по умолчанию 100) выводит направление движения игрока в чат.
sampRegisterChatCommand('getDirection', function(waitms)
    -- аргумент - раз в сколько мс выводить направление
    waitms = tonumber(waitms)
    if not waitms then
        waitms = 100
    end
    lua_thread.create(function()
        while true do
            local Xstart, Ystart, _ = getCharCoordinates(PLAYER_PED)
            wait(waitms)
            local Xend, Yend, _ = getCharCoordinates(PLAYER_PED)
            sampAddChatMessage(getDirection(Xstart, Ystart, Xend, Yend, waitms), -1)
        end
    end)
end)
 
Последнее редактирование:

Receiver

🥩 Передай meat, всё в скип, я в темпе
Проверенный
596
805
Описание: легальная посадка в транспорт, с анимацией. Хз чё по задержке, поставил 5000 мс.
Lua:
function legalCarEnter(carHandle_)
    if doesVehicleExist(carHandle_) then -- Проверяем существует ли транспорт
        local bRes, vehicleId = sampGetVehicleIdByCarHandle(carHandle_); -- Получаем SAMP ID транспорта
        if bRes then -- Если удалось получить
            sampSendEnterVehicle(vehicleId, false); -- Отправляем синхру посадки в транспорт
            taskEnterCarAsDriver(PLAYER_PED, carHandle_, 5000); -- Включаем анимацию посадки
        end
    end
end
Пример использования:
Lua:
legalCarEnter(ХЕНЛД_КАРА);
 
  • Нравится
Реакции: RoflHaHaWF, Tema05 и Cosmo

Fomikus

Известный
Проверенный
469
337
Описание: Рисует переливающуюся или радужную линию (Использует функции FYP и rraggerr)
qIj4qnM9k1.gif

Lua:
function join_argb(a, r, g, b) -- by FYP
    local argb = b  -- b
    argb = bit.bor(argb, bit.lshift(g, 8))  -- g
    argb = bit.bor(argb, bit.lshift(r, 16)) -- r
    argb = bit.bor(argb, bit.lshift(a, 24)) -- a
    return argb
end

function rainbow(speed, alpha, offset) -- by rraggerr
    local clock = os.clock() + offset
    local r = math.floor(math.sin(clock * speed) * 127 + 128)
    local g = math.floor(math.sin(clock * speed + 2) * 127 + 128)
    local b = math.floor(math.sin(clock * speed + 4) * 127 + 128)
    return r,g,b,alpha
end

function rainbow_line(distance, size) -- by Fomikus
    local op = imgui.GetCursorPos()
    local p = imgui.GetCursorScreenPos()
    for i = 0, distance do
    r, g, b, a = rainbow(1, 255, i / -50)
    imgui.GetWindowDrawList():AddRectFilled(imgui.ImVec2(p.x + i, p.y), imgui.ImVec2(p.x + i + 1, p.y + size), join_argb(a, r, g, b))
    end
    imgui.SetCursorPos(imgui.ImVec2(op.x, op.y + size + imgui.GetStyle().ItemSpacing.y))
end

function static_rainbow_line(distance, size) -- by Fomikus
    local op = imgui.GetCursorPos()
    local p = imgui.GetCursorScreenPos()
    for i = 0, distance do
    r, g, b, a = rainbow_v2(1, 255, i / -50)
    imgui.GetWindowDrawList():AddRectFilled(imgui.ImVec2(p.x + i, p.y), imgui.ImVec2(p.x + i + 1, p.y + size), join_argb(a, r, g, b))
    end
    imgui.SetCursorPos(imgui.ImVec2(op.x, op.y + size + imgui.GetStyle().ItemSpacing.y))
end

function rainbow_v2(speed, alpha, offset) -- by rraggerr
    local r = math.floor(math.sin(offset * speed) * 127 + 128)
    local g = math.floor(math.sin(offset * speed + 2) * 127 + 128)
    local b = math.floor(math.sin(offset * speed + 4) * 127 + 128)
    return r,g,b,alpha
end
Пример использования:
Lua:
local imgui  = require 'imgui'

local speed = imgui.ImInt(1)
local rb_line_size = imgui.ImInt(-50)
imgui.Process = true

function imgui.OnDrawFrame()
        imgui.SetNextWindowSize(imgui.ImVec2(500, 180), main_window_state, imgui.Cond.FirstUseEver)
        if not window_pos then
            ScreenX, ScreenY = getScreenResolution()
            imgui.SetNextWindowPos(imgui.ImVec2(0, 0), imgui.Cond.FirsUseEver, imgui.ImVec2(0.5, 0.5))
            window_pos = true
        end
        imgui.Begin('##Window', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoScrollbar + imgui.WindowFlags.NoTitleBar)
        imgui.Text('Line 1')
        rainbow_line(250, 50)
        imgui.Text('Line 2')
        rainbow_line(500, 10)
        imgui.SliderInt("rb_line_size", rb_line_size, -1000, 1000)
        imgui.SliderInt("Speed", speed, 0, 10)
        static_rainbow_line(250, 10)
        imgui.End()
end

function join_argb(a, r, g, b) -- by FYP
    local argb = b  -- b
    argb = bit.bor(argb, bit.lshift(g, 8))  -- g
    argb = bit.bor(argb, bit.lshift(r, 16)) -- r
    argb = bit.bor(argb, bit.lshift(a, 24)) -- a
    return argb
end

function rainbow(speed, alpha, offset) -- by rraggerr
    local clock = os.clock() + offset
    local r = math.floor(math.sin(clock * speed) * 127 + 128)
    local g = math.floor(math.sin(clock * speed + 2) * 127 + 128)
    local b = math.floor(math.sin(clock * speed + 4) * 127 + 128)
    return r,g,b,alpha
end

function rainbow_line(distance, size) -- by Fomikus
    local op = imgui.GetCursorPos()
    local p = imgui.GetCursorScreenPos()
    for i = 0, distance do
    r, g, b, a = rainbow(speed.v, 255, i / rb_line_size.v)
    imgui.GetWindowDrawList():AddRectFilled(imgui.ImVec2(p.x + i, p.y), imgui.ImVec2(p.x + i + 1, p.y + size), join_argb(a, r, g, b))
    end
    imgui.SetCursorPos(imgui.ImVec2(op.x, op.y + size + imgui.GetStyle().ItemSpacing.y))
end

function static_rainbow_line(distance, size) -- by Fomikus
    local op = imgui.GetCursorPos()
    local p = imgui.GetCursorScreenPos()
    for i = 0, distance do
    r, g, b, a = rainbow_v2(speed.v, 255, i / rb_line_size.v)
    imgui.GetWindowDrawList():AddRectFilled(imgui.ImVec2(p.x + i, p.y), imgui.ImVec2(p.x + i + 1, p.y + size), join_argb(a, r, g, b))
    end
    imgui.SetCursorPos(imgui.ImVec2(op.x, op.y + size + imgui.GetStyle().ItemSpacing.y))
end

function rainbow_v2(speed, alpha, offset) -- by rraggerr
    local r = math.floor(math.sin(offset * speed) * 127 + 128)
    local g = math.floor(math.sin(offset * speed + 2) * 127 + 128)
    local b = math.floor(math.sin(offset * speed + 4) * 127 + 128)
    return r,g,b,alpha
end

p.s Значения к сожалению кривые(Нельзя просто изменить размер или скорость). Если rb_line_size положительное - справа налево, если отрицательно - слева направо.
Если хотите изменить скорость, при этом не теряя размер - умножьте размер на отношение новой и прошлой скорости.
Например:
Нам понравилась картинка при размере -50 и скорости 1, но я хочу чтобы она летела со скростью 10.
Тогда размер будет равен -500 (-50 * (10 / 1))
 

_raz0r

t.me/sssecretway | ТГК: t.me/razor_code
Модератор
1,889
3,041
Описание: *Изменяет цвет текста в EditBox чата*
Lua:
function editChatEditBoxTextColor(color)
    local pInput = memory.read(getModuleHandle("samp.dll") + 0x21A0E8, 4, true)
    local pEditInputBox = memory.read(pInput + 0x8, 4, true)
    memory.write(pEditInputBox + 0x127, color, 4, true)
end
Пример использования:
Lua:
function main()    
     editChatEditBoxTextColor(0xFF00FF00) -- argb color (Green)
end
1596781236358.png

Описание: *Изменяет цвет текста в EditBox диалога*
Lua:
function editDialogEditBoxTextColor(color)
    local pDialog = memory.read(getModuleHandle("samp.dll") + 0x21A0B8, 4, true)
    local pEditBox = memory.read(pDialog + 0x24, 4, true)
    memory.write(pEditBox + 0x127, color, true)
end
Пример использования:
Lua:
function main()    
     editDialogEditBoxTextColor(0xFF00FF00) -- argb color (Green)
end
 
Последнее редактирование: