Jump to content

Lord Henry

Other Languages Moderators
  • Posts

    3,932
  • Joined

  • Last visited

  • Days Won

    174

Posts posted by Lord Henry

  1. Tente isso:

    -- SERVER-SIDE
    function vehicleHPVerify(loss)
        if getElementHealth(source) - loss < 300 then
            -- setVehicleDamageProof (source, true) -- Neste caso não funciona. Faz com que este evento não seja mais acionado.
            setVehicleEngineState (source, false)
            setElementHealth(source, 300)
            local thePlayer = getVehicleController (source)
            if thePlayer then
                outputChatBox ("Seu veículo quebrou o motor. Chame um mecânico.", thePlayer)
            end
            cancelEvent()
        end
    end
    addEventHandler ("onVehicleDamage", root, vehicleHPVerify)
    
    function antiVehicleEngine (cmd)
        if cmd == "motor" then
            local theVehicle = getPlayerOccupiedVehicle (source)
            if theVehicle then
                if getPedOccupiedVehicleSeat (source) == 0 then
                    if getElementHealth (theVehicle) <= 300 then
                        setVehicleEngineState (theVehicle, false)          
                        cancelEvent()
                    end
                end
            end
        end
    end
    addEventHandler ("onPlayerCommand", root, antiVehicleEngine)
    
    addEventHandler("onVehicleEnter", root, function(thePlayer)
        if getElementHealth(source) <= 300 then
            setVehicleEngineState(source, false)
            outputChatBox ("Este veículo está com o motor quebrado. Chame um mecânico.", thePlayer)
        end
    end)

     

  2. Desta forma:

    Client-side:

    local screenW, screenH = guiGetScreenSize()
    local painel = false
    -- Layout Fixo: (centralizado)
    local layout = {
        -- posX, posY, sizeX, sizeY, colorRGBA, text, textColorRGBA, fontSize, fontFamily, alignX, alignY
        {-320, -180, 640, 360, tocolor(75, 75, 75, 255)}, -- Window
        {-320, -190, 426, 20, tocolor(23, 209, 248, 255)}, -- Tittle Line
        {-300, -160, 600, 60, tocolor(20, 20, 20, 255), "Arsenal", tocolor(255, 255, 255, 255), 3, "bankgothic", "center", "center"}, -- Tittle
        {-300, -80, 186, 100, tocolor(43, 43, 43, 255), "M4", tocolor(255, 255, 255, 255), 2, "pricedown", "center", "center"}, -- Button 1
        {-300, 40, 186, 100, tocolor(43, 43, 43, 255), "AK", tocolor(255, 255, 255, 255), 2, "pricedown", "center", "center"}, -- Button 2
        {-93, -80, 186, 100, tocolor(43, 43, 43, 255), "GLOCK", tocolor(255, 255, 255, 255), 2, "pricedown", "center", "center"}, -- Button 3
        {-93, 40, 186, 100, tocolor(43, 43, 43, 255), "Skin 1", tocolor(255, 255, 255, 255), 2, "pricedown", "center", "center"}, -- Button 4
        {114, -80, 186, 100, tocolor(43, 43, 43, 255), "Skin 2", tocolor(255, 255, 255, 255), 2, "pricedown", "center", "center"}, -- Button 5
        {114, 40, 186, 100, tocolor(43, 43, 43, 255), "VEICULO", tocolor(255, 255, 255, 255), 2, "pricedown", "center", "center"}, -- Button 6
        {-320, 140, 640, 40, false, "Para fechar aperte 'Backspace'", tocolor(255, 255, 255, 255), 2, "default", "center", "center"}, -- Close info
    }
    
    function paineldx ()
        for i, infos in ipairs (layout) do -- Para cada item da tabela layout, faça:
            local posX, posY, sizeX, sizeY, colorRGBA, text, textColorRGBA, fontSize, fontFamily, alignX, alignY = unpack (infos) -- Separa as infos em variáveis.
            -- Layout Fixo:
            posX = (screenW / 2) + posX -- Faz com que o centro da tela seja a posição 0, 0. Centralizando as posições.
            posY = (screenH / 2) + posY -- Converte as posições centralizadas da tabela para posições absolutas.
            
            if colorRGBA then -- Só faz dxDrawRectangle se tiver o parâmetro colorRGBA. Se não tiver, é só um texto isolado.
                if i >= 4 and i <= 9 then -- Se for um botão, então: (se for do item 4 até o 9)
                    if isMouseInPosition (posX, posY, sizeX, sizeY) then -- Se o mouse está em cima do botão, então:
                        colorRGBA = tocolor(0, 0, 0, 255) -- Torna a cor do botão preto.
                    end
                end
                dxDrawRectangle(posX, posY, sizeX, sizeY, colorRGBA, false)
            end
            if text then -- Só faz dxDrawText se tiver o parâmetro texto.
                sizeX = posX + sizeX
                sizeY = posY + sizeY
                dxDrawText(text, posX, posY, sizeX, sizeY, textColorRGBA, fontSize, fontFamily, alignX, alignY)
            end
        end
    end
    
    addEvent("HitM", true)
    addEventHandler("HitM", root, function() -- Função chamada pelo servidor quando este jogador colide no marker do server.
        if not painel then
            addEventHandler("onClientRender", root, paineldx)
            painel = true
            showCursor(true)
        end
    end)
    
    bindKey("backSpace", "down", function() -- Tecla que fecha o painel.
        if painel then
            removeEventHandler("onClientRender", root, paineldx)
            painel = false
            showCursor(false)
        end
    end)
    
    addEventHandler("onClientClick", root, function(button, state)
        if button == "left" and state == "down" then
            if painel then
                for i, infos in pairs (layout) do -- Neste caso uso pairs pois a ordem dos itens não importa.
                    local posX, posY, sizeX, sizeY = unpack (infos) -- Separa as infos em variáveis.
                    -- Layout Fixo:
                    posX = (screenW / 2) + posX -- Converte a posição centralizada da tabela para posição absoluta.
                    posY = (screenH / 2) + posY
    
                    if isMouseInPosition(posX, posY, sizeX, sizeY) then
                        if i == 4 then -- Se for o botão de M4, então:
                            triggerServerEvent("setarAlgo", localPlayer, "weapon", 31, 9999)
                            -- giveWeapon (source, 31, 9999) -- Não funciona client-side.
                        elseif i == 5 then -- Se for o botão de AK, então:
                            triggerServerEvent("setarAlgo", localPlayer, "weapon", 30, 9999)
                        elseif i == 6 then -- Se for o botão de Glock, então:
                            triggerServerEvent("setarAlgo", localPlayer, "weapon", 24, 9999)
                        elseif i == 7 then -- Se for o botão de Skin 1, então:
                            triggerServerEvent("setarAlgo", localPlayer, "skin", 28)
                        elseif i == 8 then -- Se for o botão de Skin 2, então:
                            triggerServerEvent("setarAlgo", localPlayer, "skin", 29)
                        elseif i == 9 then -- Se for o botão de Vehicle, então:
                            triggerServerEvent("setarAlgo", localPlayer, "vehicle", 560)
                        end
                    end
                end
            end
        end
    end)
    
    function isMouseInPosition (x, y, width, height) -- Função útil.
        if not isCursorShowing() then return false end
        local sx, sy = guiGetScreenSize()
        local cx, cy = getCursorPosition()
        local cx, cy = (cx * sx), (cy * sy)
        
        return ((cx >= x and cx <= x + width) and (cy >= y and cy <= y + height))
    end

    Server-side:

    local m1 = createMarker(2027.903, 1545.603, 10.819 -1, "cylinder", 1.5, 0,195,255, 100)
    local vehicles = {}
    
    addEventHandler("onMarkerHit", m1, function(hit)
        if getElementType(hit) == "player" then -- Se quem colidiu no marker for um jogador, então:
            if isObjectInACLGroup ("user."..getAccountName (getPlayerAccount (hit)), aclGetGroup ("Admin")) then -- Se o jogador está na ACL Admin, então:
                setTimer(triggerClientEvent, 250, 1, hit, "HitM", hit)
            else
                outputChatBox("Acesso negado.", hit, 255, 0, 0)
            end
        end
    end)
    
    addEvent("setarAlgo", true)
    addEventHandler("setarAlgo", root, function (tipo, id, ammo) -- Função chamada pelo client. Seta algo no jogador.
        if tipo == "weapon" then
            giveWeapon(client, id, ammo, true)
        elseif tipo == "skin" then
            setElementModel (client, id)
        elseif tipo == "vehicle" then
            local x, y, z = getElementPosition(client)
            if isElement (vehicles[client]) then -- Se já existe um veículo criado por este jogador, então:
                destroyElement(vehicles[client]) -- Destrói esse veículo antes de criar outro.
            end
            vehicles[client] = createVehicle(id, x, y, z + 1) -- Cria o veículo em cima do jogador.
        end
    end)
    
    function limpaVehicle() -- Destrói o veículo criado pelo jogador quando ele sair do servidor.
        if isElement (vehicles[source]) then
            destroyElement(vehicles[source])
            vehicles[source] = nil
        end
    end
    addEventHandler("onPlayerQuit", root, limpaVehicle)
    addEventHandler("onPlayerDisconnect", root, limpaVehicle)

     

    • Thanks 1
  3. @JPzin comece fazendo o seguinte:

    1. Corrija a indentação dos seus códigos para que eles fiquem legíveis.
      Para aprender a indentar código, veja este tópico.
    2. Troque todos os getRootElement() por root.

    Depois de fazer o básico, aí sim você pode começar a corrigir o painel.

    1. De cara, a função giveWeapon é server-side. Portanto não vai funcionar no seu script client-side.
    2. Vi que seu painel foi feito usando escala relativa para tentar manter o painel no mesmo tamanho em qualquer resolução, porém isso dará problema com os textos pois eles não acompanham a escala da tela e precisam que você declare tamanhos diferentes na fonte.
      1. Ou você faz um painel de tamanho fixo (no máximo 640x480), evitando problemas com os textos e evitando trabalho.
      2. Ou você calcula a resolução do jogador e aplica no tamanho da fonte junto, o que dará mais trabalho.
      3. Ao usar escala relativa, você também precisa se preocupar com a proporção da tela, algumas resoluções são mais quadradas (4:3), outras são mais retangulares (16:9), causando distorções no painel e deixando ele mais esticado ou comprimido na horizontal. Nestes casos, você precisa definir tamanhos de fonte diferente na horizontal também, saiba mais em dxDrawText.
    3. Evite repetição de código. Crie uma tabela com todas as posições e tamanhos de cada botão junto com os textos. Então dentro da função do onClientRender você apenas faz um "loop ipairs" entre os itens dessa tabela, gerando os botões com as propriedades da tabela.
    4. Na função do onClientClick, você usa a mesma tabela para verificar qual botão foi clicado, criando uma condição para cada índice da tabela. Ex: Se clicou no item 1 da tabela, faz tal coisa. Senão, se clicou no item 2 da tabela, faz outra coisa e assim por diante.
    5. Para facilitar na hora de fazer manutenção no painel, deixe cada dxDraw com comentários no final da linha dizendo o que é cada item. Por exemplo, no final da linha do primeiro dxDrawRectangle, adicione o comentário: -- Janela

    Só então, depois do painel pronto, você deve criar feedback visual ao passar o mouse pelas áreas clicáveis. Já que o objetivo de um painel DX é ser mais bonito do que funcional. Se fosse pra ser mais funcional do que bonito, você deveria usar CEGUI em vez de DXGUI.

    1. Ao passar o mouse em cima de um botão, mude a cor dele para o jogador saber que é uma área clicável. Ou então mude a cor do texto do botão.

     

     

  4. Crie uma variável com valor 0. Por exemplo playersArena = 0

    Sempre que um jogador entrar, aumente em +1 nessa variável: playersArena = playersArena + 1

    Sempre que um jogador sair ou desconectar do servidor, diminua em -1 essa variável: playersArena = playersArena - 1

    Dai no texto, apenas mostre o valor dessa variável com um tostring(playersArena).

  5. Client:

    Spoiler
    local shop_gui = {tab = {},tabpanel = {},label = {},gridlist = {},window = {},button = {},memo = {}}
    
    local shop = {
        ["ls_graveyard"] = {
            ["normal"] = {
                ["supply_dealer"] = {815.20001220703,-1108.6999511719,25.799999237061,0.00274658},
                ["vehicle_dealer"] = {815.5,-1092.5,25.799999237061,178.000488},
                ["supply_dealer_marker"] = {815.20001220703,-1108.6999511719,25.799999237061,0.00274658},
                ["vehicle_dealer_marker"] = {815.5,-1092.5,25.799999237061,835.40002441406,-1103.3000488281,24.299999237061,0,0,0}, -- {marker_x,marker_y,marker_z,vehicle_spawn_x,vehicle_spawn_y,vehicle_spawn_z,rx,ry,rz}
            },
        },
    }
    
    local shop_items = {
        ["normal"] = {
            ["supply"] = {
                -- example: {"itemdata",amount,price};
                ["Weapons"] = {
                    {"weapon11",1,50},
                    {"weapon21",1,20},
                    {"weapon23",1,15},
                    {"weapon20",1,30},
                },
                ["Ammo"] = {
                    {"mag5",20,12},
                    {"mag1",15,12},
                    {"mag3",30,12},
                },
                ["Food"] = {
                    {"fooditem4",1,10},
                    {"fooditem5",1,10},
                    {"fooditem1",1,10},
                },
                ["Parts"] = {
                    {"vehiclepart1",1,25},
                    {"vehiclepart2",1,25},
                    {"vehiclepart3",1,25},
                    {"vehiclepart4",1,25},
                    {"vehiclepart5",1,25}
                },
                ["Backpacks"] = {
                    {"backpack4",1,15},
                    {"backpack3",1,25},
                    {"backpack2",1,35},
                },
                ["Toolbelts"] = {
                    {"toolbelt4",1,10},
                },
                --["Convert"] = {
                --  {"zKill Bag",1,10},
                --},
            },
            ["vehicle"] = {
                ["Vehicles"] = {
                    -- example: {"name",id,engine,rotor,tires,tankparts,scrap,slots,fuel,price}
                    {"Armored Truck",528,1,0,4,1,1,50,80,500},
                    {"HMMWV",470,1,0,4,1,1,46,100,100},
                    {"Pickup Truck",422,1,0,4,1,1,25,80,80},
                    {"Motorcycle",468,1,0,2,1,1,10,30,60},
                    {"Old Bike",509,0,0,0,0,0,0,0,30},
                },
            },
        },
    }
    
    -- local currency_item = "zombieskilled"; -- SUBSTITUÍDO POR MONEY.
    
    --{[ DO NOT CHANGE THEESE ]}--
    local shop_marker = nil;
    local shop_marker_type = nil;
    local shop_humanity_type = nil;
    local vehicle_spawn_position = nil;
    local vehicle_spawn_position_col = {};
    --{[ DO NOT CHANGE THEESE ]}--
    
    
    function load_shop()
        for i,v in pairs(shop) do
            local current_shop = i;
            for i,v in pairs(v) do
                if (i ~= "items") then
                    local humanity_type = i;
                    for i,v in pairs(v) do
                        if (i == "supply_dealer") then
                            local supplyDealer = createPed(29,v[1],v[2],v[3],v[4],false)
                            createBlipAttachedTo(supplyDealer, 6)
                            setElementFrozen(supplyDealer,true)
                            setPedVoice(supplyDealer, "PED_TYPE_DISABLED")
                            addEventHandler("onClientRender",root,function()
                                -- dxDrawTextOnElement(supplyDealer,"supply dealer",0.25,10,0,0,0,255,1.02,"sans") -- Sombra será criada diretamente na função útil.
                                dxDrawTextOnElement(supplyDealer,"supply dealer",0.26,10,0,200,100,255,1,"sans")
                            end)
                        elseif (i == "vehicle_dealer") then
                            local vehicleDealer = createPed(28,v[1],v[2],v[3],v[4],false)
                            createBlipAttachedTo(vehicleDealer, 55)
                            setPedVoice(vehicleDealer, "PED_TYPE_DISABLED")
                            setElementFrozen(vehicleDealer,true)
                            addEventHandler("onClientRender",root,function()
                                -- dxDrawTextOnElement(vehicleDealer,"vehicle dealer",0.25,10,0,0,0,255,1.02,"sans") -- Sombra será criada diretamente na função útil.
                                dxDrawTextOnElement(vehicleDealer,"vehicle dealer",0.26,10,0,200,100,255,1,"sans")
                            end)
                        elseif (i == "supply_dealer_marker") then
                            local supplyShopMarker = createMarker(v[1],v[2],v[3]-1,"cylinder",2,0,255,0,0)
                            addEventHandler("onClientMarkerHit",supplyShopMarker,function(player)
                                if (player == localPlayer) then
                                        guiSetVisible(shop_gui.window[1],true)
                                        setTimer(guiSetText, 500, 1, shop_gui.label[1], " Pesos (PHP): "..getPlayerMoney(localPlayer))
                                        showCursor(true)
                                        shop_marker = current_shop;
                                        shop_marker_type = "supply";
                                        shop_humanity_type = humanity_type;
                                        updateShop();
                                end
                            end)
                            addEventHandler("onClientMarkerLeave",supplyShopMarker,function(player)
                                if (player == localPlayer) then
                                        guiSetVisible(shop_gui.window[1],false)
                                        showCursor(false)
                                        if (isEventHandlerAdded("onClientGUIClick",shop_gui.gridlist[1],updateItems)) then
                                            removeEventHandler("onClientGUIClick",shop_gui.gridlist[1],updateItems)
                                        end
                                        shop_marker = nil;
                                        shop_marker_type = nil;
                                        shop_humanity_type = nil;
                                        killErrorMessageTimer();
                                end
                            end)
                        elseif (i == "vehicle_dealer_marker") then
                            local vehicleShopMarker = createMarker(v[1],v[2],v[3]-1,"cylinder",2,0,255,0,0)
                            vehicle_spawn_position_col[current_shop] = createColSphere(v[4],v[5],v[6],4.5)
                            addEventHandler("onClientMarkerHit",vehicleShopMarker,function(player)
                                if (player == localPlayer) then    
                                        guiSetVisible(shop_gui.window[1],true)
                                        setTimer(guiSetText, 500, 1, shop_gui.label[1], " Pesos (PHP): "..getPlayerMoney(localPlayer))
                                        showCursor(true)
                                        vehicle_spawn_position = {v[4],v[5],v[6],v[7],v[8],v[9]}
                                        shop_marker = current_shop;
                                        shop_marker_type = "vehicle";
                                        shop_humanity_type = humanity_type;
                                        updateShop();
                                end
                            end)
                            addEventHandler("onClientMarkerLeave",vehicleShopMarker,function(player)
                                if (player == localPlayer) then
                                        guiSetVisible(shop_gui.window[1],false)
                                        showCursor(false)
                                        if (isEventHandlerAdded("onClientGUIClick",shop_gui.gridlist[1],updateItems)) then
                                            removeEventHandler("onClientGUIClick",shop_gui.gridlist[1],updateItems)
                                        end
                                        shop_marker = nil;
                                        shop_marker_type = nil;
                                        shop_humanity_type = nil;
                                        vehicle_spawn_position = nil;
                                        killErrorMessageTimer();
                                end
                            end)
                        end
                    end
                end
            end
        end
    end
    addEvent("load_shop",true);
    addEventHandler("load_shop",root,load_shop);
    
    addEventHandler("onClientResourceStart",resourceRoot,function()
        if getElementData(localPlayer,"logedin") then
            load_shop();
        end
    end);
    
    function killErrorMessageTimer()
        if isTimer(errorMessageTimer) then
            killTimer(errorMessageTimer)
            guiSetText(shop_gui.label[4],"")
            guiSetAlpha(shop_gui.label[4],1)
        end
    end
    
    function buyItem()
        if isTimer(errorMessageTimer) then
            killTimer(errorMessageTimer)
            guiSetText(shop_gui.label[4],"")
            guiSetAlpha(shop_gui.label[4],1)
            errorMessageTimer = setTimer(removeErrorMessage,275,15)
        else
            function removeErrorMessage()
                if (guiGetAlpha(shop_gui.label[4]) > 0.30) then
                    guiSetAlpha(shop_gui.label[4],guiGetAlpha(shop_gui.label[4])-0.05)
                elseif (guiGetAlpha(shop_gui.label[4]) < 0.30) then
                    if isTimer(errorMessageTimer) then killTimer(errorMessageTimer) end
                    guiSetText(shop_gui.label[4],"")
                    guiSetAlpha(shop_gui.label[4],1)
                end
            end
            errorMessageTimer = setTimer(removeErrorMessage,275,15)
        end
     
        if (guiGridListGetSelectedItem(shop_gui.gridlist[2] ) == -1) then
            guiSetText(shop_gui.label[4],"Please select an item")
            guiLabelSetColor (shop_gui.label[4],255,0,0)
        elseif (shop_marker_type == "supply") then
            local target = localPlayer;
            local item = guiGridListGetItemText(shop_gui.gridlist[2], guiGridListGetSelectedItem(shop_gui.gridlist[2]),1)
            local amount,price,itemdata = unpack(guiGridListGetItemData(shop_gui.gridlist[2], guiGridListGetSelectedItem(shop_gui.gridlist[2]),2))
            guiLabelSetColor(shop_gui.label[4],255,0,0)
    
            -- if (getElementData(localPlayer, currency_item) >= price) then
            if getPlayerMoney(localPlayer) >= price then
                guiSetText(shop_gui.label[4],"You successfully bought "..item..".")
                guiLabelSetColor (shop_gui.label[4],0,149,14,255)
                -- triggerServerEvent("DayZPH:onClientSuccessBuysItem",localPlayer,target,itemdata,currency_item,amount,price)
                triggerServerEvent("DayZPH:onClientSuccessBuysItem", localPlayer, target, itemdata, amount, price)
                setTimer(guiSetText, 500, 1, shop_gui.label[1], " Pesos (PHP): "..getPlayerMoney(localPlayer))
            else
                guiSetText(shop_gui.label[4],"You don't have enough money (PHP) to buy utilities")
            end
        elseif (shop_marker_type == "vehicle") then
            local target = localPlayer;
            local vehicleName = guiGridListGetItemText(shop_gui.gridlist[2], guiGridListGetSelectedItem(shop_gui.gridlist[2]),1)
            local id,engine,rotor,tires,tankparts,scrap,slots,fuel,price = unpack(guiGridListGetItemData(shop_gui.gridlist[2],guiGridListGetSelectedItem(shop_gui.gridlist[2]),1))
            local x,y,z,rx,ry,rz = unpack(vehicle_spawn_position)
            guiLabelSetColor(shop_gui.label[4],255,0,0)
            -- if (getElementData(localPlayer,currency_item) >= price) then
            if getPlayerMoney(localPlayer) >= price then
                for i,v in ipairs(getElementsWithinColShape(vehicle_spawn_position_col[shop_marker],"vehicle")) do
                    guiSetText(shop_gui.label[4],"Vehicle spawn area is taken, clear it before buying vehicle.")
                    return
                end
                guiSetVisible(shop_gui.window[1],false)
                showCursor(false)
                outputChatBox("You successfully bought "..vehicleName..".",0,255,0)
                -- triggerServerEvent("DayZPH:onClientSuccessBuysVehicle",localPlayer,target,currency_item,price,x,y,z,rx,ry,rz,id,engine,rotor,tires,tankparts,scrap,slots,fuel)
                
                triggerServerEvent("DayZPH:onClientSuccessBuysVehicle",localPlayer,target,price,x,y,z,rz,ry,rx,id,engine,rotor,tires,tankparts,scrap,slots,fuel)
                setTimer(guiSetText, 500, 1, shop_gui.label[1], " Pesos (PHP): "..getPlayerMoney(localPlayer))
            else
                guiSetText(shop_gui.label[4], "You don't have enough money (PHP) to buy a car")
            end
        end
    end
    
    addEventHandler("onClientGUIClick",resourceRoot,function()
        if (source == shop_gui.button[1]) then
            buyItem();
        elseif (source == shop_gui.button[2]) then
            if getElementData(localPlayer, "logedin") then
                if (guiGetVisible(shop_gui.window[1]) == true) then
                    guiSetVisible( shop_gui.window[1], false )
                    showCursor(false)
                    if (isEventHandlerAdded("onClientGUIClick",shop_gui.gridlist[1],updateItems)) then
                        removeEventHandler("onClientGUIClick",shop_gui.gridlist[1],updateItems)
                    end
                    shop_marker = nil;
                    shop_marker_type = nil;
                    shop_humanity_type = nil;
                    vehicle_spawn_position = nil;
                    killErrorMessageTimer();
                end
            end
        end
    end)
    
    -- addEventHandler("onClientElementDataChange",root,function(data)
    -- addEvent("onClientBuyItem")
    --     if getElementData(localPlayer, "logedin") then
    --         if (string.find(data,currency_item)) then
    --             guiSetText(shop_gui.label[1], " Pesos (PHP): "..getElementData(localPlayer, currency_item))
    --         end
    --     end
    -- end)
    
    addEventHandler("onClientResourceStart",resourceRoot,function()
        local screenW, screenH = guiGetScreenSize()
        shop_gui.window[1] = guiCreateWindow((screenW - 481) / 2, (screenH - 245) / 2, 551, 245, "Shop", false)
        guiWindowSetSizable(shop_gui.window[1], false)
        guiSetVisible(shop_gui.window[1],false)
        guiSetProperty(shop_gui.window[1],"AlwaysOnTop","True");
     
        shop_gui.tabpanel[1] = guiCreateTabPanel(10, 26, 380, 231, false, shop_gui.window[1])
     
        shop_gui.tab[1] = guiCreateTab("Buy", shop_gui.tabpanel[1])
     
        shop_gui.gridlist[1] = guiCreateGridList(5, 5, 102, 176, false, shop_gui.tab[1])
        guiGridListAddColumn(shop_gui.gridlist[1], "Category", 0.8)
        guiSetProperty(shop_gui.gridlist[1],"SortSettingEnabled","False")
        shop_gui.gridlist[2] = guiCreateGridList(107, 5, 267, 176, false, shop_gui.tab[1])
        guiGridListAddColumn(shop_gui.gridlist[2], "", 0.5)
        guiGridListAddColumn(shop_gui.gridlist[2], "Price", 0.4)
        guiSetProperty(shop_gui.gridlist[2],"SortSettingEnabled","False")
     
        shop_gui.gridlist[3] = guiCreateGridList(395, 48, 146, 188, false, shop_gui.window[1])
     
        shop_gui.button[1] = guiCreateButton(4, 152, 100, 32, "BUY", false, shop_gui.gridlist[3])
        shop_gui.button[2] = guiCreateButton(104, 152, 38, 32, "X", false, shop_gui.gridlist[3])
        shop_gui.label[1] = guiCreateLabel(10, 131, 130, 15, " Pesos (PHP): 0", false, shop_gui.gridlist[3])
     
        shop_gui.memo[1] = guiCreateMemo(10, 10, 126, 118, "Dealer: Welcome to DayZ Philippines Black Market! Be careful here because people can kill you in this area.", false, shop_gui.gridlist[3])
        guiSetProperty(shop_gui.memo[1], "Disabled", "True")
        guiSetAlpha(shop_gui.memo[1],0.7)
     
        --[[ shop_gui.tab[2] = guiCreateTab("Sell", shop_gui.tabpanel[1])
        guiSetEnabled(shop_gui.tab[2],false)/  ]]--
     
        shop_gui.label[4] = guiCreateLabel(187, 22, 349, 26, "", false, shop_gui.window[1])
        guiLabelSetHorizontalAlign(shop_gui.label[4], "right", false)
        guiLabelSetVerticalAlign(shop_gui.label[4], "center")
     
        function updateShop()
            guiGridListClear(shop_gui.gridlist[1])
            guiGridListClear(shop_gui.gridlist[2])
            if (shop_marker_type == "supply") then
                guiSetText(shop_gui.window[1],"Supply Shop")
                guiGridListSetColumnTitle(shop_gui.gridlist[2],1,"Item")
     
                -- loads categories
                for i,v in pairs(shop_items) do
                    if (i == shop_humanity_type) then
                        for i,v in pairs(v) do
                            if (i == shop_marker_type) then
                                for i,v in pairs(v) do
                                    local row = guiGridListAddRow(shop_gui.gridlist[1])
                                    guiGridListSetItemText(shop_gui.gridlist[1], row, 1, i, false, false)
                                end
                            end
                        end
                    end
                end
     
                -- loads items from player choosed category
                function updateItems()
                    guiGridListClear(shop_gui.gridlist[2])
                    local category = guiGridListGetItemText(shop_gui.gridlist[1],guiGridListGetSelectedItem(shop_gui.gridlist[1]))
                    if (category ~= "") then
                        for i,v in pairs(shop_items) do
                            if (i == shop_humanity_type) then
                                for i,v in pairs(v) do
                                    if (i == shop_marker_type) then
                                        for i,v in ipairs(v[category]) do
                                            local row = guiGridListAddRow(shop_gui.gridlist[2])
                                            guiGridListSetItemText(shop_gui.gridlist[2], row, 1, exports.dayzepoch:getLanguageTextClient(v[1]), false, false)
                                            guiGridListSetItemText(shop_gui.gridlist[2], row, 2, v[3], false, false)
                                            guiGridListSetItemData(shop_gui.gridlist[2], row, 2, {v[2],v[3],v[1]})
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
                addEventHandler("onClientGUIClick",shop_gui.gridlist[1],updateItems,false)
            elseif (shop_marker_type == "vehicle") then
                guiSetText(shop_gui.window[1],"Vehicle Shop")
                guiGridListSetColumnTitle(shop_gui.gridlist[2],1,"Vehicle")
     
                -- loads categories
                for i,v in pairs(shop_items) do
                    if (i == shop_humanity_type) then
                        for i,v in pairs(v) do
                            if (i == shop_marker_type) then
                                for i,v in pairs(v) do
                                    local row = guiGridListAddRow(shop_gui.gridlist[1])
                                    guiGridListSetItemText(shop_gui.gridlist[1], row, 1, i, false, false)
                                end
                            end
                        end
                    end
                end
     
                -- loads items from player choosed category
                function updateItems()
                    guiGridListClear(shop_gui.gridlist[2])
                    local category = guiGridListGetItemText(shop_gui.gridlist[1],guiGridListGetSelectedItem(shop_gui.gridlist[1]))
                    if (category ~= "") then
                        for i,v in pairs(shop_items) do
                            if (i == shop_humanity_type) then
                                for i,v in pairs(v) do
                                    if (i == shop_marker_type) then
                                        for i,v in ipairs(v[category]) do
                                            local row = guiGridListAddRow(shop_gui.gridlist[2])
                                            guiGridListSetItemText(shop_gui.gridlist[2], row, 1, v[1], false, false)
                                            guiGridListSetItemText(shop_gui.gridlist[2], row, 2, v[10], false, false)
                                            guiGridListSetItemData(shop_gui.gridlist[2], row, 1, {v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10]})
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
                addEventHandler("onClientGUIClick",shop_gui.gridlist[1],updateItems,false)
            end
        end
    end)
    
    -- [[ SOME USEFUL FUNCTIONS ]]
    
    function isEventHandlerAdded( sEventName, pElementAttachedTo, func )
        if type( sEventName ) == 'string' and isElement( pElementAttachedTo ) and type( func ) == 'function' then
        local aAttachedFunctions = getEventHandlers( sEventName, pElementAttachedTo )
            if type( aAttachedFunctions ) == 'table' and #aAttachedFunctions > 0 then
                for i, v in ipairs( aAttachedFunctions ) do
                    if v == func then
                    return true
                    end
                end
            end
        end
        return false
    end
    
    function dxDrawTextOnElement(TheElement,text,height,distance,R,G,B,alpha,size,font,checkBuildings,checkVehicles,checkPeds,checkDummies,seeThroughStuff,ignoreSomeObjectsForCamera,ignoredElement)
        local x, y, z = getPedBonePosition(TheElement,6)
        local x2, y2, z2 = getPedBonePosition(localPlayer,6)
        local distance = distance or 20
        local height = height or 1
        local checkBuildings = checkBuildings or true
        local checkVehicles = checkVehicles or false
        local checkPeds = checkPeds or false
        local checkObjects = checkObjects or true
        local checkDummies = checkDummies or true
        local seeThroughStuff = seeThroughStuff or false
        local ignoreSomeObjectsForCamera = ignoreSomeObjectsForCamera or false
        local ignoredElement = ignoredElement or nil
        if (isLineOfSightClear(x, y, z, x2, y2, z2, checkBuildings, checkVehicles, checkPeds , checkObjects,checkDummies,seeThroughStuff,ignoreSomeObjectsForCamera,ignoredElement)) then
            local sx, sy = getScreenFromWorldPosition(x, y, z+height)
            if(sx) and (sy) then
                local distanceBetweenPoints = getDistanceBetweenPoints3D(x, y, z, x2, y2, z2)
                if(distanceBetweenPoints < distance) then
                    dxDrawText(text, sx+2, sy+2, sx, sy, tocolor(0, 0, 0, 255), (size or 1), font or "arial", "center", "center") -- Shadow
                    dxDrawText(text, sx, sy, sx, sy, tocolor(R or 255, G or 255, B or 255, alpha or 255), (size or 1), font or "arial", "center", "center") -- Text
                end
            end
        end
    end

     

    Server:

    Spoiler
    -- give item if all went success
    function onClientSuccessBuysItem(target,item,amount,price)
        if getPlayerMoney(target) < price then return end
        setElementData(target,item,getElementData(target,item)+amount)
        -- setElementData(target,"money",getElementData(target,"money")-price)
        takePlayerMoney(target, price)
    end   
    addEvent("DayZPH:onClientSuccessBuysItem", true)
    addEventHandler("DayZPH:onClientSuccessBuysItem", root, onClientSuccessBuysItem)
     
    -- spawn vehicle if all went success
    function onClientSuccessBuysVehicle(target,price,x,y,z,rx,ry,rz,id,engine,rotor,tires,tankparts,scrap,slots,fuel)
        -- if getElementData(target,currency) < price then return; end
        if getPlayerMoney(target) < price then return end
        local veh = createVehicle(id,x,y,z,rx,ry,rz);
        print(id,x,y,z,rx,ry,rz)
        local vehCol = createColSphere(x,y,z,2.5);
        if (id == 528) then setVehicleDamageProof(veh,true); end
        attachElements(vehCol,veh);
        setElementData(vehCol,"parent",veh);
        setElementData(veh,"parent",vehCol);
        setElementData(vehCol,"vehicle",true);
        setElementData(veh,"dayzvehicle",0);
        setElementData(vehCol,"MAX_Slots",tonumber(slots));
        setElementData(vehCol,"Engine_inVehicle",engine);
        setElementData(vehCol,"Rotor_inVehicle",rotor);
        setElementData(vehCol,"Tire_inVehicle",tires);
        setElementData(vehCol,"Parts_inVehicle",tankparts);
        setElementData(vehCol,"Scrap_inVehicle",scrap);
        setElementData(vehCol,"needtires", tires);
        setElementData(vehCol,"needparts", tankparts);
        setElementData(vehCol,"needscrap", scrap);
        setElementData(vehCol,"needrotor", rotor);
        setElementData(vehCol,"needengines", engine);
        setElementData(vehCol,"spawn",{id,x,y,z});
        setElementData(vehCol,"fuel",fuel);
        -- setElementData(target,currency,getElementData(target,currency)-price)
        takePlayerMoney(target, price)
    end
    addEvent("DayZPH:onClientSuccessBuysVehicle",true)
    addEventHandler("DayZPH:onClientSuccessBuysVehicle", root, onClientSuccessBuysVehicle)
     
    addEventHandler("onPlayerLogin", root, function()
        triggerClientEvent(source,"load_shop",source);
    end);

     

     

  6. Olha... vc só mudou 1 variável. Mas não trocou os getElementData/setElementData para getPlayerMoney/setPlayerMoney.

    Além disso, getPlayerMoneysetPlayerMoney devem ser feitos server-side somente. Então você precisará de triggerServerEvent ali no script client-side para chamar um evento lá no server-side para mexer no dinheiro no jogador. Até pq tentar setar dinheiro no jogador via client-side só mudará na Hud, mas não vai mudar no servidor, então o dinheiro que aparece na Hud não será a quantidade real que ele tem no servidor.

    • Like 1
  7. Após analisar seu código, fiz um exemplo parecido com sua ideia.

    Independente da resolução, ele vai ter a mesma proporção e distância da borda da tela.

    local screen = Vector2 (guiGetScreenSize()) -- local screen.x, screen.y = guiGetScreenSize()
    local offset = screen.y * 0.01852 -- Distância relativa da borda da tela. (0 = colado na borda)
    --[[
        ~20px = 0.01852
        ~15px = 0.01389
        ~10px = 0.00926
    ]]
    local bgScale, circleScale = (screen.y * 0.04), 0.9 -- Raio dos círculos background relativos à tela | Raio dos círculos em relação aos círculos background.
    -- (1 = tamanho Y da tela | 1 = tamanho igual aos círculos de background)
    local iconScale = bgScale * 0.5 -- Tamanho relativo dos ícones em relação ao tamanho dos backgrounds. (1 = tamanho igual aos círculos de background)
    local circleAngle = 270 -- Ângulo que os backgrounds e os círculos começam a ser preenchidos. (0 = direita, 90 = abaixo, 180 = esquerda, 270 = acima)
    
    addEventHandler("onClientRender", root, function()
        local health = getElementHealth(localPlayer)
        local armor = getPedArmor(localPlayer)
    
        dxDrawCircle (offset + bgScale, screen.y - bgScale - offset, bgScale, 0, 360, tocolor(28, 28, 28, 170)) -- bg Health
        dxDrawCircle (offset + bgScale, screen.y - bgScale - offset, bgScale * circleScale, 0 + circleAngle, (360 * (health/100)) + circleAngle, tocolor(255, 32, 32)) -- Health
        -- dxDrawImage (ícone da vida)
        
        if armor > 0 then -- Faz com que o círculo de armor só apareça se não estiver em 0.
            dxDrawCircle ((offset + bgScale) + (bgScale * 1.4), screen.y - bgScale - offset, bgScale, 0, 360, tocolor(28, 28, 28, 170)) -- bg Armor
            dxDrawCircle ((offset + bgScale) + (bgScale * 1.4), screen.y - bgScale - offset, bgScale * circleScale, 0 + circleAngle, (360 * (armor/100)) + circleAngle, tocolor(255, 255, 255)) -- Armor
            -- dxDrawImage (ícone do colete)
        end
    end)

     

    Spoiler

    image.thumb.jpeg.0119b648210ed8e69071058f6f07885c.jpeg


     

  8. objeto = createObject (1337, 2502, -1667, 12.36) -- Cria um objeto qualquer na Grove Street.
    
    addEventHandler("onClientRender", root, function()
        -- for _, objeto in ipairs(getElementsByType("object")) do -- DESATIVADOS APENAS PARA TESTES.
            -- if (getElementData(objeto,"objeto.element")) then
                -- local ID = getElementData(objeto, "objeto.id")
                -- local PD = getElementData(objeto, "objeto.produtos")
                local ID = 1337       -- APENAS PARA TESTES
                local PD = 1234567890 -- APENAS PARA TESTES
                
                local localPos = {getElementPosition(localPlayer)}
                local objetoPos = {getElementPosition(objeto)}
                
                local worldPosition = {getScreenFromWorldPosition(objetoPos[1], objetoPos[2], objetoPos[3] + 0.50)}
                local distance = getDistanceBetweenPoints3D(localPos[1], localPos[2], localPos[3], objetoPos[1], objetoPos[2], objetoPos[3])
                if distance <= 15 then
                    if worldPosition[1] and worldPosition[2] then
                        dxDrawText("ID: "..ID.." | PD: "..PD, worldPosition[1], worldPosition[2], worldPosition[1], worldPosition[2], tocolor(255, 255, 255, 255), 1.0 , "default-bold", "center")
                    end
                end
        --     end
        -- end -- DESATIVADOS APENAS PARA TESTES.
    end)

    image.png.335b50ef899ca59b356a9423654cde0d.png

    • Thanks 1
  9. O seu 4º e 5º parâmetros não fazem sentido. (10, 20)

    Também não faz sentido vc colocar "center" fora de aspas duplas. Este parâmetro é uma string, portanto precisa estar entre aspas, exatamente como mencionei na minha resposta anterior.

    O primeiro "center" faz ele centralizar o texto na horizontal, o segundo "center" faz ele centralizar na vertical, mas não é necessário centralizar na vertical nesse caso, pois é só aumentar o diminuir aquele offset do + 0.50 para mudar a altura do texto. Então utilize apenas o primeiro "center" e delete o que tem depois.

     

    • Thanks 1
  10. A culpa é inteiramente da administração do servidor. As possíveis causas são as seguintes:

    1) Não desenvolveram uma segurança decente para o servidor, permitindo que os jogadores violem os banimentos.

    2) Desenvolveram resources com brechas de segurança que tornaram o servidor violável pelos clientes.

    3) Deram permissão admin para algum resource desconhecido que está colocando usuários não autorizados na ACL Group Console.

  11. Para fazer com que o jogador não consiga abrir o chatbox pela tecla T (isso também vai impedir que ele use o teamsay pela tecla Y), você pode simplesmente desativar o controle de acesso do chatbox com isso: (client-side)

    -- CLIENT-SIDE
    addEventHandler("onClientResourceStart", resourceRoot, function() -- Executa essa função ao iniciar este resource no client.
        toggleControl("chatbox", false) -- Bloqueia o acesso ao chatbox pelas teclas T e Y, mas ainda é possível enviar mensagens e comandos pelo F8.
        showChat (false) -- Esta função torna o chat invisível para este client.
        -- O jogador ainda pode restaurar o chat pelo comando "showchat" no F8. Mas ele continuará inacessível pelo T e Y devido ao toggleControl.
        -- Após restaurar o chat pelo F8, o jogador pode mandar mensagens e comandos pelo F8 também.
    end)

    Para evitar as mensagens de "say" e "teamsay" pelo F8, use isso: (server-side)

    -- SERVER-SIDE
    local cmdBloqueados = {"say", "teamsay"} -- Lista de comandos bloqueados.
    
    addEventHandler("onPlayerCommand", root, function(command)
        for _,cmd in pairs(cmdBloqueados) do
            if (command == cmd) then
                cancelEvent() -- Só consegue bloquear comandos server-side.
                break
            end
        end
    end)

    Com isso você torna impossível usar o chatbox. Comandos server-side você pode bloquear adicionando ali na lista. Mas os comandos client-side não podem ser bloqueados por questões de segurança.

×
×
  • Create New...