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

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,771
11,214
Описание:
  • TransformRealWorldPointToRadarSpace - конвертирует 3д координаты в координаты на радаре
  • TransformRadarPointToScreenSpace - конвертирует координаты радара в экранные
  • IsPointInsideRadar - проверяет находится ли точка в рамках радара (в качестве аргумента нужно использовать значения, полученные через TransformRealWorldPointToRadarSpace)
Код:
Lua:
local ffi = require('ffi')
ffi.cdef('struct CVector2D {float x, y;}')
local CRadar_TransformRealWorldPointToRadarSpace = ffi.cast('void (__cdecl*)(struct CVector2D*, struct CVector2D*)', 0x583530)
local CRadar_TransformRadarPointToScreenSpace = ffi.cast('void (__cdecl*)(struct CVector2D*, struct CVector2D*)', 0x583480)
local CRadar_IsPointInsideRadar = ffi.cast('bool (__cdecl*)(struct CVector2D*)', 0x584D40)

function TransformRealWorldPointToRadarSpace(x, y)
    local RetVal = ffi.new('struct CVector2D', {0, 0})
    CRadar_TransformRealWorldPointToRadarSpace(RetVal, ffi.new('struct CVector2D', {x, y}))
    return RetVal.x, RetVal.y
end

function TransformRadarPointToScreenSpace(x, y)
    local RetVal = ffi.new('struct CVector2D', {0, 0})
    CRadar_TransformRadarPointToScreenSpace(RetVal, ffi.new('struct CVector2D', {x, y}))
    return RetVal.x, RetVal.y
end

function IsPointInsideRadar(x, y)
    return CRadar_IsPointInsideRadar(ffi.new('struct CVector2D', {x, y}))
end
Lua:
local ffi = require('ffi')
ffi.cdef('struct CVector2D {float x, y;}')

function TransformRealWorldPointToRadarSpace(x, y)
    local RetVal = ffi.new('struct CVector2D', {0, 0})
    ffi.cast('void (__cdecl*)(struct CVector2D*, struct CVector2D*)', 0x583530)(RetVal, ffi.new('struct CVector2D', {x, y}))
    return RetVal.x, RetVal.y
end

function TransformRadarPointToScreenSpace(x, y)
    local RetVal = ffi.new('struct CVector2D', {0, 0})
    ffi.cast('void (__cdecl*)(struct CVector2D*, struct CVector2D*)', 0x583480)(RetVal, ffi.new('struct CVector2D', {x, y}))
    return RetVal.x, RetVal.y
end

function IsPointInsideRadar(x, y)
    return ffi.cast('bool (__cdecl*)(struct CVector2D*)', 0x584D40)(ffi.new('struct CVector2D', {x, y}))
end
Пример использования: отрисовка айди игроков на метках
Lua:
for _, ped in ipairs(getAllChars()) do
    local result, id = sampGetPlayerIdByCharHandle(ped)
    if result then
        local RadarX, RadarY = TransformRealWorldPointToRadarSpace(getCharCoordinates(ped))
        if IsPointInsideRadar(RadarX, RadarY) then
            local x, y = TransformRadarPointToScreenSpace(RadarX, RadarY)
            local text = sampIsPlayerNpc(id) and 'NPC' or id
            local textSize = { x = renderGetFontDrawTextLength(Font, text), y = renderGetFontDrawHeight(Font) }
            renderFontDrawText(Font, text, x - textSize.x / 2, y, sampGetPlayerColor(id))
            if sampIsCursorActive() then -- show text if ID hovered
                local curX, curY = getCursorPos()
                if curX > x - textSize.x / 2 and curX < x + textSize.x / 2 and curY > y and curY < y + textSize.y then
                    renderFontDrawText(Font, ('%s [%d] LVL: %d'):format(sampGetPlayerNickname(id), id, sampGetPlayerScore(id)), x + 20, y, sampGetPlayerColor(id))
                end
            end
        end
    end
end
1668455329654.png

(не спрашивайте что за квадрокоптер у меня вместо радардиска)

Еще один пример использования:
Lua:
local RadarX, RadarY = TransformRealWorldPointToRadarSpace(0, 0)
local x, y = TransformRadarPointToScreenSpace(RadarX, RadarY)
if IsPointInsideRadar(RadarX, RadarY) then
    renderFontDrawText(Font, 'ПРОДАМ ГАРАЖ, КУПЛЮ АЙФОН', x, y, 0xFFffffff)
end
1668455740349.png
1668456160512.png
 
Последнее редактирование:

SADFI2259X

Участник
92
76

KnobFloat​

final-6375296b692a7e02bde98e8b-7.gif


Lua:
function imgui.KnobFloat(label, p_value, v_min, v_max)
    local p_value = p_value.v
  
    local style = imgui.GetStyle()
    local io = imgui.GetIO()
  
    local radius_outer = 20.0
    local pos = imgui.GetCursorScreenPos()
    local center = imgui.ImVec2(pos.x + radius_outer, pos.y + radius_outer)
    local line_height = imgui.GetTextLineHeight()
    local draw_list = imgui.GetWindowDrawList()

    local ANGLE_MIN = 3.141592 * 0.75
    local ANGLE_MAX = 3.141592 * 2.25

    imgui.InvisibleButton(label, imgui.ImVec2(radius_outer * 2, radius_outer * 2 + line_height + style.ItemInnerSpacing.y))
    local value_changed = false
    local is_active = imgui.IsItemActive()
    local is_hovered = imgui.IsItemActive()
    if is_active and not io.MouseDelta.x == 0.0 then
        local step = (v_max - v_min) / 200.0
        p_value = p_value + io.MouseDelta.x * step
        if (p_value < v_min) then p_value = v_min end
        if (p_value > v_max) then p_value = v_max end
        value_changed = true
    end
  
    if is_active then
        col = imgui.GetStyle().Colors[imgui.Col.FrameBgActive]
    else
        col = imgui.GetStyle().Colors[imgui.Col.FrameBgHovered]
    end

    local t = (p_value - v_min) / (v_max - v_min)
    local angle = ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * t
    local angle_cos = math.cos(angle)
    local angle_sin = math.sin(angle)
    local radius_inner = radius_outer * 0.40
    draw_list:AddCircleFilled(center, radius_outer, imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.FrameBg]), 16)
    draw_list:AddLine(imgui.ImVec2(center.x + angle_cos * radius_inner, center.y + angle_sin * radius_inner), imgui.ImVec2(center.x + angle_cos * (radius_outer - 2), center.y + angle_sin * (radius_outer - 2)), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.SliderGrabActive]), 2.0)
    draw_list:AddCircleFilled(center, radius_inner, imgui.GetColorU32(col), 16)
    draw_list:AddText(imgui.ImVec2(pos.x, pos.y + radius_outer * 2 + style.ItemInnerSpacing.y), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.Text]), label)

    if (is_active or is_hovered) then
        imgui.SetNextWindowPos(imgui.ImVec2(pos.x - style.WindowPadding.x, pos.y - line_height - style.ItemInnerSpacing.y - style.WindowPadding.y))
        imgui.BeginTooltip()
        imgui.Text(string.format('%.3f', (p_value)))
        imgui.EndTooltip()
    end

    return value_changed
end
https://github.com/ocornut/imgui/issues/942#issuecomment-268369298
 
Последнее редактирование:

ARMOR

kjor32 is legend
Модератор
4,851
6,081
Описание: Изменяет цвет следов крови на земле.

Код:
Lua:
local memory = require 'memory'

memory.setuint8(0x49EDDB, A, true)
memory.setuint8(0x49EDD6, R, true)
memory.setuint8(0x49EDD2, B, true)
memory.setuint8(0x49EDD4, G, true)

Скриншот:
Знімок екрана 2022-11-17 165201.png


Описание: Включает/Выключает тепловизор

Код:
Lua:
local ffi = require 'ffi'

--Использование: termalVision(true/false)

function termalVision(enable)
    ffi.cast('void(__cdecl*)(bool)', 0x701140)(ffi.cast('bool', enable))
end

Описание: Включает/Выключает прибор ночного виденья:

Код:
Lua:
local ffi = require 'ffi'

--Использование: nightVision(true/false)

function nightVision(enable)
    ffi.cast('void(__cdecl*)(bool)', 0x701120)(ffi.cast('bool', enable))
end
 
Последнее редактирование:

BARRY BRADLEY

Известный
711
176
Описание: Изменяет цвет следов крови на земле.

Код:
Lua:
local memory = require 'memory'

memory.setuint8(0x49EDDB, A, true)
memory.setuint8(0x49EDD6, R, true)
memory.setuint8(0x49EDD2, B, true)
memory.setuint8(0x49EDD4, G, true)

Скриншот:
Посмотреть вложение 178022

Описание: Включает/Выключает тепловизор

Код:
Lua:
local ffi = require 'ffi'

--Использование: termalVision(true/false)

function termalVision(enable)
    ffi.cast('void(__cdecl*)(bool)', 0x701140)(ffi.cast('bool', enable))
end

Описание: Включает/Выключает прибор ночного виденья:

Код:
Lua:
local ffi = require 'ffi'

--Использование: nightVision(true/false)

function nightVision(enable)
    ffi.cast('void(__cdecl*)(bool)', 0x701120)(ffi.cast('bool', enable))
end
Чем setNightVision и setInfraredVision не те?
 
  • Вау
Реакции: ARMOR

Vespan

loneliness
Проверенный
2,103
1,633
Прекольный radiobutton как в андроиде(у себя на прошивке pixel experience увидел и решил сделать)).
1668710800080.png

Lua:
function imgui.AndroidRadioButton(label,v,int)
    local bool,hovered = false,false
    local DL = imgui.GetWindowDrawList()
    local p = imgui.GetCursorScreenPos()
    imgui.SetCursorPosY(imgui.GetCursorPosY()-3)
    if imgui.InvisibleButton(label,imgui.ImVec2((8*3)+imgui.CalcTextSize(label).x,8+8+2)) then;    v.v = int; bool = true;    end
    if imgui.IsItemHovered() then hovered = true end
    if v.v == int then
        DL:AddCircleFilled(imgui.ImVec2(p.x+5+5,p.y+(5/2)),5,imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.Text]),20,2)
    end
    DL:AddCircle(imgui.ImVec2(p.x+8+2,p.y+3),8,imgui.GetColorU32(imgui.GetStyle().Colors[hovered and imgui.Col.Text or ( v.v == int and imgui.Col.Text or imgui.Col.FrameBgHovered)]),20,2)
    DL:AddText(imgui.ImVec2(p.x+8+8+8,p.y-3.5),-1,label)
    return bool
end
Lua:
imgui.AndroidRadioButton('test',int,1)
imgui.AndroidRadioButton('test2',int,2)
imgui.AndroidRadioButton(u8'хочупитсу',int,3)
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,771
11,214
Описание: возвращает тип транспорта
Код:
Lua:
local Is__Model = {
    {'IsBoatModel',         0x4C5A70, 'Boat'},
    {'IsCarModel',          0x4C5AA0, 'Car'},
    {'IsTrainModel',        0x4C5AD0, 'Train'},
    {'IsHeliModel',         0x4C5B00, 'Heli'},
    {'IsPlaneModel',        0x4C5B30, 'Plane'},
    {'IsBikeModel',         0x4C5B60, 'Bike'},
    {'IsFakePlaneModel',    0x4C5B90, 'FakePlane'},
    {'IsMonsterTruckModel', 0x4C5BC0, 'MonsterTruck'},
    {'IsQuadBikeModel',     0x4C5BF0, 'QuadBike'},
    {'IsBmxModel',          0x4C5C20, 'Bicycle'},
    {'IsTrailerModel',      0x4C5C50, 'Trailer'},
}
for k, v in ipairs(Is__Model) do _G['__'..v[1]] = ffi.cast('bool (__cdecl *)(int)', v[2]) end

function getVehicleType(modelId)
    for k, v in ipairs(Is__Model) do
        if _G['__'..v[1]](modelId) then return v[3] end
    end
    return 'unknown'
end
Пример использования:
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('currentvehicletype', function()
        if not isCharInAnyCar(PLAYER_PED) then
            return sampAddChatMessage('Доступно только в транспорте!', 0xFFff0000)
        end
        local veh = storeCarCharIsInNoSave(PLAYER_PED) -- получаем хендл машины в которой сидит игрок
        local carModel = getCarModel(veh) -- получаем айди модели машины по хендлу
        local vehType = getVehicleType(carModel) -- получаем тип транспорта
        sampAddChatMessage('Тип вашего транспорта: '..vehType, -1)
        --[[
            все предыдущие строки можно заменить на:
            sampAddChatMessage('Тип вашего транспорта: '..getVehicleType(getCarModel(storeCarCharIsInNoSave(PLAYER_PED))), -1)
        ]]
        
    end)
    wait(-1)
end
 
Последнее редактирование:

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,771
11,214
Описание: небольшой шаблон для написания ботов (бег к каждой точке из массива). При прохождении каждой точки вызывает указанную вами функцию, в качестве аргумента передает в функцию номер пройденной точки.
Код:
Lua:
local Bot = {
    Points = {
        {x = -0.092503599822521, y = 14.050937652588, z = 3.1171875},
        {x = 15.137202262878, y = -0.69070810079575, z = 3.1171875},
        {x = 37.457454681396, y = 11.805542945862, z = 3.1171875},
    },
    callback = function(passedPointIndex)
        sampAddChatMessage('Пройдена точка #'..passedPointIndex, -1)
    end,
    Sprint = true,
}
function WBot(Bot)
    lua_thread.create(function()
        for index, data in ipairs(Bot.Points) do
            data.dist = data.dist or 1
            if not data.done then
                while getDistanceBetweenCoords3d(data.x, data.y, data.z, getCharCoordinates(PLAYER_PED)) > data.dist do
                    wait(0)
                    taskCharSlideToCoord(PLAYER_PED, data.x, data.y, data.z, 0, data.dist)
                    if Bot.Sprint then
                        setGameKeyState(16, 256)
                    end
                end
                if not data.done then -- anti callback flood
                    Bot.Points[index].done = true
                    Bot.callback(index)
                end
            end
        end
    end)
end
Пример использования:
Lua:
-- function WBot

local Bot = {
    Points = {
        {x = -0.092503599822521, y = 14.050937652588, z = 3.1171875},
        {x = 15.137202262878, y = -0.69070810079575, z = 3.1171875},
        {x = 37.457454681396, y = 11.805542945862, z = 3.1171875},
    },
    Sprint = true
}

Bot.callback = function(passedPointIndex)
    sampAddChatMessage('Пройдена точка #'..passedPointIndex, -1)
    if passedPointIndex == #Bot.Points then
        sampAddChatMessage('Все точки пройдены, бот выключен', -1)
    end
end

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('start', function()
        active = not active
        printStyledString('BOT '..(active and '~g~ON' or '~r~OFF'), 1000, 7)
        if active then
            for k, v in ipairs(Bot.Points) do
                Bot.Points[k].done = false
            end
        end
    end)
    while true do
        wait(0)
        if active then
            WBot(Bot)
        end
    end
end
 

why ega

РП игрок
Модератор
2,541
2,233
Описание: Проверяет, инициализирован SAMP или нет (без использования SAMPFUNCS.asi). Кому не лень, можете дать оффсеты для других версий.
Код:
Lua:
local ffi = require("ffi")

function isSAMPRunning()
    local handle = getModuleHandle("samp.dll")
    local result = true
    if handle ~= nil then
        local e_lfanew = ffi.cast("long*", handle + 60)[0]
        local nt_header = handle + e_lfanew
        local entry_point_addr = ffi.cast("unsigned int*", nt_header + 40)[0]
        if entry_point_addr == 0x31DF13 then -- R1
            result = result and ffi.cast("unsigned int*", handle + 0x21A0F8)[0] ~= 0x0
        elseif entry_point_addr == 0x3195DD then -- R2
            result = result and ffi.cast("unsigned int*", handle + 0x21A100)[0] ~= 0x0
        elseif entry_point_addr == 0xCC4D0 then -- R3
            result = result and ffi.cast("unsigned int*", handle + 0x26E8DC)[0] ~= 0x0        
        elseif entry_point_addr == 0xCBCB0 then -- R4
            result = result and ffi.cast("unsigned int*", handle + 0x26EA0C)[0] ~= 0x0
        elseif entry_point_addr == 0xFDB60 then -- R5
            result = result and ffi.cast("unsigned int*", handle +  0x26EB94)[0] ~= 0x0
        end
    end
    return result
end
Пример использования:
Lua:
--========================================================LIB-========================================================

local ffi = require("ffi")

--========================================================MAIN========================================================

function main()
    while not isSAMPRunning() do wait(100) end

    sampAddChatMessage("ЭТО САМП ДЕТКААА", -1)

    wait(-1)
end

--========================================================FUNCTION========================================

function isSAMPRunning()
    local handle = getModuleHandle("samp.dll")
    local result = true
    if handle ~= nil then
        local e_lfanew = ffi.cast("long*", handle + 60)[0]
        local nt_header = handle + e_lfanew
        local entry_point_addr = ffi.cast("unsigned int*", nt_header + 40)[0]
        if entry_point_addr == 0x31DF13 then -- R1
            result = result and ffi.cast("unsigned int*", handle + 0x21A0F8)[0] ~= 0x0
        elseif entry_point_addr == 0x3195DD then -- R2
            result = result and ffi.cast("unsigned int*", handle + 0x21A100)[0] ~= 0x0
        elseif entry_point_addr == 0xCC4D0 then -- R3
            result = result and ffi.cast("unsigned int*", handle + 0x26E8DC)[0] ~= 0x0        
        elseif entry_point_addr == 0xCBCB0 then -- R4
            result = result and ffi.cast("unsigned int*", handle + 0x26EA0C)[0] ~= 0x0
        elseif entry_point_addr == 0xFDB60 then -- R5
            result = result and ffi.cast("unsigned int*", handle +  0x26EB94)[0] ~= 0x0
        end
    end
    return result
end
 
Последнее редактирование:

Savchik Blazer

Но я, мечту свою лелея...
Проверенный
671
293
Описание: Проверяет, инициализирован SAMP или нет (без использования SAMPFUNCS.asi). Кому не лень, можете дать оффсеты для других версий.
Код:
Lua:
local ffi = require("ffi")

function isSAMPRunning()
    local handle = getModuleHandle("samp.dll")
    local result = true

    if handle ~= nil then
        local e_lfanew = ffi.cast("long*", handle + 60)[0]
        local nt_header = handle + e_lfanew
        local entry_point_addr = ffi.cast("unsigned int*", nt_header + 40)[0]
        if entry_point_addr == 0x31DF13 then -- R1
            result = result and ffi.cast("unsigned int*", handle + 0x21A0F8)[0] ~= 0x0
        elseif entry_point_addr == 0xCC4D0 then -- R3
            result = result and ffi.cast("unsigned int*", handle + 0x26E8DC)[0] ~= 0x0
        end
    end

    return result
end
Пример использования:
Lua:
--========================================================LIB-========================================================

local ffi = require("ffi")

--========================================================MAIN========================================================

function main()
    while not isSAMPRunning() do wait(100) end

    sampAddChatMessage("ЭТО САМП ДЕТКААА", -1)

    wait(-1)
end

--========================================================FUNCTION========================================

function isSAMPRunning()
    local handle = getModuleHandle("samp.dll")
    local result = true

    if handle ~= nil then
        local e_lfanew = ffi.cast("long*", handle + 60)[0]
        local nt_header = handle + e_lfanew
        local entry_point_addr = ffi.cast("unsigned int*", nt_header + 40)[0]
        if entry_point_addr == 0x31DF13 then -- R1
            result = result and ffi.cast("unsigned int*", handle + 0x21A0F8)[0] ~= 0x0
        elseif entry_point_addr == 0xCC4D0 then -- R3
            result = result and ffi.cast("unsigned int*", handle + 0x26E8DC)[0] ~= 0x0
        end
    end

    return result
end
Код:
R2 -> 0x21A100
R4 -> 0x26EA0C
 
  • Нравится
Реакции: qdIbp и why ega

ARMOR

kjor32 is legend
Модератор
4,851
6,081
Описание: Добавляет сообщение о смерти в killList:

Код:
Lua:
local ffi = require 'ffi'

function addKillMessage(szKiller, szVictim, killerColor, victimColor, weapon)
    local pDeathWindow = memory.getuint32(getModuleHandle('samp.dll') + 0x21A0EC, true) -- R3 0x26E8D0
    ffi.cast('void(__thiscall*)(void* pDeathWindow, const char* szKiller, const char* szVictim, unsigned long killerColor, unsigned long victimColor, char nWeapon)', getModuleHandle('samp.dll') + 0x66930)(ffi.cast('void*', pDeathWindow), szKiller, szVictim, killerColor, victimColor, weapon) -- R3 0x69E60
end

Описание: Опускает ползунок чата на самый низ:

Код:
Lua:
local ffi = require 'ffi'

function scrollChatToBottom()
    local pChat = memory.getuint32(getModuleHandle('samp.dll') + 0x21A0E4) -- R3 0x26E8C8
    ffi.cast('void(__thiscall*)(void* pChat)', getModuleHandle('samp.dll') + 0x637C0)(ffi.cast('void*', pChat)) -- R3 0x66C10
end
 
  • Нравится
Реакции: why ega

eqzzz

Участник
126
19
Описание: Получает модель ПК. Получает из реестра, из-за этого сворачивается игра.
Использование: print(getModelName())
Код:
Lua:
function getModelName()
    local handle = io.popen('reg.exe QUERY HKLM\\SYSTEM\\HardwareConfig\\Current /v SystemProductName')
    local result = handle:read("*a")
    local model_name = result:match('REG_SZ%s+(.+)'):gsub("%s+", "")
    handle:close()
    return model_name
end
 

E E E E E E E

Участник
115
15
Описание: Ищет маркер на карте.
Использование: local result, x, y, z = SearchMarker(posX, posY, posZ, radius, isRace)
Код:
Lua:
function SearchMarker(posX, posY, posZ, radius, isRace)
    local ret_posX = 0.0
    local ret_posY = 0.0
    local ret_posZ = 0.0
    local isFind = false

    for id = 0, 31 do
        local MarkerStruct = 0
        if isRace then MarkerStruct = 0xC7F168 + id * 56
        else MarkerStruct = 0xC7DD88 + id * 160 end
        local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
        local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
        local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))

        if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
            if getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ) < radius then
                ret_posX = MarkerPosX
                ret_posY = MarkerPosY
                ret_posZ = MarkerPosZ
                isFind = true
                radius = getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ)
            end
        end
    end

    return isFind, ret_posX, ret_posY, ret_posZ
end

Пример:
Lua:
script_dependencies("CLEO", "SAMP", "SAMPFUNCS")

---------------------------------------------------------------------------

require "lib.moonloader"
require "lib.sampfuncs"

---------------------------------------------------------------------------

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    sampRegisterChatCommand("mycmd", cmd)

    while true do wait(0) end
end

function cmd(param)
    if isPlayerPlaying(playerHandle) then
        local posX, posY, posZ = getCharCoordinates(playerPed)
        local res, x, y, z = SearchMarker(posX, posY, posZ, 50.0, false)
        if res then
            sampAddChatMessage(string.format("Найден обычный маркер в координатах %.2f %.2f %.2f", x, y, z), -1)
        else
            res, x, y, z = SearchMarker(posX, posY, posZ, 50.0, true)
            if res then
                sampAddChatMessage(string.format("Найден гоночный маркер в координатах %.2f %.2f %.2f", x, y, z), -1)
            else
                sampAddChatMessage("Маркер не найден", -1)
            end
        end
    end
end

function SearchMarker(posX, posY, posZ, radius, isRace)
    local ret_posX = 0.0
    local ret_posY = 0.0
    local ret_posZ = 0.0
    local isFind = false

    for id = 0, 31 do
        local MarkerStruct = 0
        if isRace then MarkerStruct = 0xC7F168 + id * 56
        else MarkerStruct = 0xC7DD88 + id * 160 end
        local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
        local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
        local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))

        if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
            if getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ) < radius then
                ret_posX = MarkerPosX
                ret_posY = MarkerPosY
                ret_posZ = MarkerPosZ
                isFind = true
                radius = getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ)
            end
        end
    end

    return isFind, ret_posX, ret_posY, ret_posZ
end
А можно подробнее рассказать как здесь асё устроено? А то я не понимаю, а просто аопипастить код не хочу
 

why ega

РП игрок
Модератор
2,541
2,233
А можно подробнее рассказать как здесь асё устроено? А то я не понимаю, а просто аопипастить код не хочу
в сампе есть такая структура, как Marker. Как я понимаю, максимальная количество чекпоинтов 32, чтобы получить адрес этой структуры в памяти мы используем условие, которое проверяет - гоночный маркер или нет. Если это гоночный чекпоинт, то к адресу структуры мы прибавляем ид чекпоинта и оффсет гоночного чекпоинта, если это не гоночный, делаем тоже самое, только меняется последний оффсет, потом чтобы получить позицию - нам надо прочитать ее из памяти, для этого м исползуем функцию readMemory(), в которой мы пишем адрес структуры маркера, полученного из условия выше и прибавляем оффсет 0, 4, 8, для каждой оси с 3д мира (representIntAsFloat представялет целое число, в виде флоат - числа с плавающей точкой - дроби), ну и дальше с 15 по 23 строку мы проверяем дистанцию, на которой находиться маркер с той, которую мы вписали в аргумент функции при вызове ее в коде. С помощью return возвращаем результат поиска и координаты
 
  • Грустно
Реакции: Lance_Sterling

Gorskin

I shit on you
Проверенный
1,247
1,043
Описание: Отключает брызги когда прыгаешь в воду и брызги когда в неё стреляют.
Lua:
memory.write(0x4A1144, 0x0004C2, 4, true)-- брызги воды когда в неё стреляют
memory.write(0x4A10D4, 0x0004C2, 4, true)-- water_splash
Отключает бурун когда плывешь в воде.
Lua:
memory.write(0x68AA70, 0x0004C2, 4, true) -- process swim effects ped
sa-mp-247.png
Отключает бурун когда ходишь по воде.
Lua:
memory.write(0x6C399F+1, 0, 4, true)
sa-mp-248.png
Отключает капли при ходьбе по воде.
Lua:
 memory.write(0x6C3606+1, 0, 4, true)
sa-mp-249.png
 
Последнее редактирование:

Foxy01

Известный
284
125
Описание: Получает текущий выворот колес у машины
1670943351920.png

Пример использования:
Lua:
angle = angle_car()
Код:
Lua:
local memory = require "memory"
function angle_car()
    local car = storeCarCharIsInNoSave(PLAYER_PED)
    local WheelAngleAdress = getCarPointer(car)+1172
    local angle = memory.getfloat(WheelAngleAdress, true)
    local temp = tostring(angle)
    local temp = temp:gsub("%d+%.", "")
    local test = string.len(temp)
    if test > 15 then
        angle = 0
    end
    return angle
end
P.S. Код не идеальный, не бейте