Jump to content

Otavio

Members
  • Posts

    28
  • Joined

  • Last visited

Everything posted by Otavio

  1. Olá estoua qui de novo, tentei fazer a database da Quilometragem por quaisquer jeito, preciso de ajudar, a como posso fazer uma mudança que possa fazer funcionar, consegui fazer isso de lógico: SERVER SIDE function RespawnHRT(veh) if source == localPlayer then local id = getElementData(veh, "ID") local KMRodeds = executeSQLQuery ("SELECT KMRodados FROM KMCarros WHERE IDCarro=?", id) driveDistance = getElementData(veh, "driveDistance") setElementData(veh, "driveDistance", KMRodeds) end end addEvent("InfoKilometragem", true) addEventHandler("InfoKilometragem", getRootElement(), RespawnHRT) function SpawnHRT(veh) if source == localPlayer then driveDistance = getElementData(veh, "driveDistance") local id = getElementData(veh, "ID") if getElementData(veh, "driveDistance") > 0 then executeSQLQuery ("INSERT INTO KMCarros(IDCarro TEXT, KMRodados INTEGER) VALUES(?,?,?)", id, driveDistance) else executeSQLQuery ("UPDATE KMCarro SET KMRodados=? WHERE IDCarro=?", driveDistance, id) end end addEvent("SetarKM", true) addEventHandler("SetarKM", getRootElement(), SpawnHRT) CLIENT SIDE local font1 = dxCreateFont("files/RobotoCondensed.ttf", 35) local SizeX, SizeY = guiGetScreenSize() local px,py = 1920,1080 local x,y = (SizeX/px), (SizeY/py) function speedometrs () if getElementData(getLocalPlayer(), "hud") == true then return end local veh = getPedOccupiedVehicle(getLocalPlayer()) if not veh or getVehicleOccupant ( veh ) ~= localPlayer then return true end if not driveDistance then lastTick = getTickCount() driveDistance = getElementData(veh, "driveDistance") or 0 end local neux, neuy, neuz = getElementPosition(veh) dxDrawText("Quilometragem "..tostring(math.round(driveDistance),1).." км",SizeX,SizeY - 100, SizeX - 380,SizeY, tocolor(255,255,255,180), 0.5,0.5, font1,"center","center") if not altx or not alty or not altz then altx, alty, altz=getElementPosition(veh) end local driveTotal = getDistanceBetweenPoints3D(neux,neuy,neuz,altx,alty,altz) driveTotal = driveTotal/1000 altx,alty,altz=neux,neuy,neuz driveDistance = math.round(driveDistance+driveTotal,3) if lastTick+5000 < getTickCount() then lastTick = getTickCount() setElementData(veh, "driveDistance", driveDistance) triggerServerEvent(SetarKM, veh) end end addEventHandler("onClientRender", root, speedometrs) addEventHandler("SetarKM", getRootElement(), speedometrs) function math.round(number, decimals, method) decimals = decimals or 0 local factor = 10 ^ decimals if (method == "ceil" or method == "floor") then return math[method](number * factor) / factor else return tonumber(("%."..decimals.."f"):format(number)) end end function EnterVehicleHRT(veh,seat) if source == localPlayer then altx, alty, altz=getElementPosition(veh) lastTick = getTickCount() driveDistance = getElementData(veh, "driveDistance") triggerServerEvent(InfoKilometragem, veh) end end addEventHandler("onClientPlayerVehicleEnter",getRootElement(), EnterVehicleHRT)
  2. @ninjaop777Aqui e discussao para a producao de script...
  3. Atualizei o meu script usando a um dos Banco de Dados explicados por Lord Henry, porem desta forma tambem nao esta salvando a quilometragem addEventHandler("onClientPlayerVehicleEnter",getRootElement(),function(veh,seat) if source == localPlayer then altx, alty, altz=getElementPosition(veh) lastTick = getTickCount() local KMRodeds = executeSQLQuery ("SELECT KMRodados FROM KMCarros WHERE IDCarro=?", id) local id = getElementData(veh, "ID") setElementData(veh, "driveDistance", KMRodeds) driveDistance = getElementData(veh, "driveDistance") end end) addEventHandler("onClientPlayerVehicleExit",getRootElement(),function(veh,seat) if source == localPlayer then driveDistance = getElementData(veh, "driveDistance") local id = getElementData(veh, "ID") executeSQLQuery ("INSERT INTO KMCarros(IDCarro TEXT, KMRodados INTEGER) VALUES(?,?,?)", id, driveDistance) executeSQLQuery ("UPDATE KMCarro SET KMRodados=? WHERE IDCarro=?", driveDistance, id) end end)
  4. Ola, achei um script de quilometragem em um site russo, porem ele nao salva tentei fazer algo, usando outros scripts, pois eh minha primeira vez, e estou usando database pela primeira vez, vou deixar meu script aqui, pra voces me ajudarem como arrumar e toda vez que o veiculo for spawnado ou alguem entrar, ganhar o KM Rodado dele novamente! addEventHandler("onResourceStart", resourceRoot, function() db = dbConnect("sqlite", "database.db") dbExec(db, "CREATE TABLE IF NOT EXISTS VehicleKM (ID, Model, KM)") for i, player in ipairs(getElementsByType("player")) do updateVehicleInfo(player) end end) addEventHandler("onVehicleEnter", getRootElement() function() local theVehicle = getPedOccupiedVehicle(source) local id = getElementData(theVehicle, "ID") local KM = getElementData(theVehicle, "driveDistance") local Model = getElementModel(theVehicle) dbExec(db, "UPDATE VehicleList WHERE ID = ? AND Model = ? AND KM = ?", id, Model, KM) end addEventHandler("onVehicleExit", getRootElement() function() local theVehicle = getPedOccupiedVehicle(source) local id = getElementData(theVehicle, "ID") local KM = getElementData(theVehicle, "driveDistance") local Model = getElementModel(theVehicle) dbExec(db, "UPDATE VehicleList WHERE ID = ? AND Model = ? AND KM = ?", id, Model, KM) end Server-Side function speedometrs () if getElementData(getLocalPlayer(), "hud") == true then return end local veh = getPedOccupiedVehicle(getLocalPlayer()) if not veh or getVehicleOccupant ( veh ) ~= localPlayer then return true end if not driveDistance then lastTick = getTickCount() driveDistance = getElementData(veh, "driveDistance") or 0 end local neux, neuy, neuz = getElementPosition(veh) dxDrawText("Quilometragem "..tostring(math.round(driveDistance),1).." км",SizeX,SizeY - 100, SizeX - 380,SizeY, tocolor(255,255,255,180), 0.5,0.5, font1,"center","center") if not altx or not alty or not altz then altx, alty, altz=getElementPosition(veh) end local driveTotal = getDistanceBetweenPoints3D(neux,neuy,neuz,altx,alty,altz) driveTotal = driveTotal/1000 altx,alty,altz=neux,neuy,neuz driveDistance = math.round(driveDistance+driveTotal,3) if lastTick+5000 < getTickCount() then lastTick = getTickCount() setElementData(veh, "driveDistance", driveDistance) end end addEventHandler("onClientRender", root, speedometrs) Client-Side Eu tentei fazer porem nao consegui
  5. Creio eu que nao tem necessidade, mas eventos como "onClientRender" sao necessarios fechar, por quando renderizam uma tabela ou algo, caso nao removem estes eventos as tabelas vao ficar aberto ate que a resource seja reiniciado ou coisa do tipo
  6. Voce deve realizar essa funcao no server! Usa-se este evento no server( onVehicleStartExit ) , nao use onVehicleExit, pois nao ira destruir o veiculo, pois o player ja estara fora dele! eu fiz um script parecido para meu servidor esses dias, que ficou desta forma function AclParaCadaCarro(source) local seat = getPedOccupiedVehicleSeat(source) local Veiculo = getPedOccupiedVehicle(source) local Conta = getAccountName(getPlayerAccount(source)) if getElementModel(Veiculo) == 416 and not isObjectInACLGroup( "user."..Conta, aclGetGroup ("SAMU")) and seat == 0 then local x, y, z = getElementPosition(Veiculo) removePedFromVehicle(source, Veiculo) setElementPosition(source, x+4, y, z) end end addEventHandler("onVehicleEnter", getRootElement(), AclParaCadaCarro) --[[ Server-Side ]]
  7. Voce basicamente so teria que adicionar () ao lado da funcao caso n tenha nenhum orientador! function Entregar_Sucata() Ficando desta forma.
  8. @Saulolno voce nao precisava trocar de script para a Hud dar certo, basicamente, voce teria que acessar o script de fome e sede e coletar a informacao de getElementData("Fome ou Sede"). E por no getElementData da Hud basicamente.
  9. Agradeço, porem voce so me deu o script pronto, aonde foi o erro que eu tive? E ainda nao esta funcionando, e apartir do triggerEvent deu mais um erro: "Bad Argument TriggerEvent at argument 2 got nil" Vou deixar aqui outras partes do script que se relacionam com essa funcao caso mais alguem queira me ajudar! --[[ Client-Side ]] function ObjetosDaLoja(_,state) if RelatividadeAgencia == true then if state == "down" then --[Gerente]-- if isCursorOnElement(x*470, y*357, x*160, y*25) then triggerServerEvent("CandidatarEmpregoGerente", source) FecharAgenciaEmpregos() setElementData(source, "Emprego", false) end end end end addEventHandler("onClientClick", getRootElement(), ObjetosDaLoja) O mesmo erro do getElementData ainda ocorre Checkei o Meta e esta Ok <meta> <script src="Client.lua" type="client"/> <script src="Ped.lua" type="client"/> <script src="Server.lua" type="server"/> <script src="GerenteTrab/server.lua" type="server" cache="false"/> <script src="GerenteTrab/client.lua" type="client" cache="false"/> <file src="Arquivos/painel.png" cache="false"/> <file src="Arquivos/perguntas.png" cache="false"/> <file src="Arquivos/respostaA.png" cache="false"/> <file src="Arquivos/respostaB.png" cache="false"/> <file src="Arquivos/respostaC.png" cache="false"/> <file src="Arquivos/respostaD.png" cache="false"/> <file src="Arquivos/agenciaA.png" cache="false"/> <file src="Arquivos/agenciaB.png" cache="false"/> <file src="Arquivos/agenciaC.png" cache="false"/> <file src="Arquivos/agenciaD.png" cache="false"/> <file src="font/abigdeal.ttf" cache="false" /> </meta>
  10. Ola, estou criando uma nova agencia de empregos, porem preciso checar se a pessoa esta no level 50, o erro eh o seguinte: Bad argument @ 'getelementdata' [expected element at argument 1, got nil] function CandidatarEmpregoGerente(source, Level) local Level = getElementData(source, "Level") or 0 if Level >= 50 then triggerClientEvent(source, "PerguntasGerente", getRootElement()) setElementData(source, "QuestaoAGENCIA", 1) setElementData(source, "Resposta", nil) end end addEvent("CandidatarEmpregoGerente", true) addEventHandler("CandidatarEmpregoGerente", getRootElement(), CandidatarEmpregoGerente) Nao sei oq fazer para arrumar se puderem me ajudar
  11. Eu adicionei porém não foi Agora foi amigo, agradeço demais por ter me ajudado!!
  12. Ainda não possui nenhum valor Linha 35 do script que você me mandou Attempt to call global 'showtime' (a nil value)
  13. Coloquei a baixo da função porém não foi function showtime() local time = getRealTime() local hours = time.hour local minutes = time.minute local seconds = time.second if (hours < 10) then hours = "0"..hours end if (minutes < 10) then minutes = "0"..minutes end if (seconds < 10) then seconds = "0"..seconds end return hours..":"..minutes..":"..seconds end function ptriniciar(thePlayer, cmd, state) local accName = getAccountName ( getPlayerAccount ( thePlayer ) ) if isObjectInACLGroup ("user."..accName, aclGetGroup ( "Policial" ) ) then if (state == "iniciar" or state == "finalizar") then -- Verifica se o comando é seguido por um parâmetro válido. local nameOfPerson = getPlayerName (thePlayer) -- Obtém o nick de quem executou o comando. local horario = showTime() if (fileExists ("logPTR.txt")) then -- Se já existe um arquivo de texto com este nome neste resource, então: newFile = fileOpen ("logPTR.txt") -- Abre o arquivo para poder editá-lo. fileSetPos (newFile, fileGetSize (newFile)) -- Coloca o cursor de escrita no fim do arquivo, caso contrário ele vai começar a escrever no começo dele, antes do que já estiver escrito no arquivo. if (state == "iniciar") then -- Se o parâmetro que o jogador usou após o comando foi "iniciar" então: outputChatBox ("Patrulha iniciada.", thePlayer) -- Apenas pra saber q o comando funcionou, normalmente teria as verificações antes de permissões e se já está em patrulha. fileWrite (newFile, "["..horario.."] "..nameOfPerson.." Iniciou sua patrulha.\n") -- Escreve isso no documento. O \n pula para a linha seguinte após a mensagem. elseif (state == "finalizar") then outputChatBox ("Patrulha finalizada.", thePlayer) fileWrite (newFile, "["..horario.."] "..nameOfPerson.." Finalizou sua patrulha.\n") end fileClose (newFile) -- Para todo fileOpen ou fileCreate, é necessário um fileClose pois enquanto arquivos estiverem abertos, eles podem ser corrompidos e os dados serão perdidos. else -- Se o arquivo ainda não existe, então: newFile = fileCreate ("logPTR.txt") -- Cria o arquivo de texto dentro deste resource e abre ele. (se já existisse um arquivo com esse nome, substituiria por um novo em branco) if (newFile) then -- Se conseguiu criar o arquivo, então: (as vezes pode dar erro de permissão no servidor, então use isso para evitar erros.) fileSetPos (newFile, fileGetSize (newFile)) if (state == "iniciar") then outputChatBox ("Patrulha iniciada.", thePlayer) fileWrite (newFile, "["..horario.."] "..nameOfPerson.." Iniciou sua patrulha.\n") elseif (state == "finalizar") then outputChatBox ("Patrulha finalizada.", thePlayer) fileWrite (newFile, "["..horario.."] "..nameOfPerson.." Finalizou sua patrulha.\n") end fileClose (newFile) else -- Se não conseguiu criar o arquivo, então: debug ("ERRO: Impossivel criar arquivo 'logPTR.txt' no servidor.") end end else -- Se não usou nenhum parâmetro após o comando ou então usou um parâmetro incorreto, então: outputChatBox ("Sintaxe: /ptr <iniciar / finalizar>", thePlayer, 255, 255, 0) end end end addCommandHandler("ptr", ptriniciar)
  14. Olá, estou mais uma vez aqui para alguém poder me ajudar, Lord Henry como sempre humilde me ajudou com um script, e eu fiz umas mudanças nele porém ele está com erro e queria uma ajuda1 o erro é: "attempt to call global 'showTime' (a nil value)" Está é a linha que possui o erro: local horario = showTime() E esté é o valor que eu dei para showTime: function showtime() local time = getRealTime() local hours = time.hour local minutes = time.minute local seconds = time.second if (hours < 10) then hours = "0"..hours end if (minutes < 10) then minutes = "0"..minutes end if (seconds < 10) then seconds = "0"..seconds end return hours..":"..minutes..":"..seconds end
  15. addCommandHandler ("ptr", getRootElement(), ptriniciar12) function ptriniciar12(thePlayer, cmd, state) local accName = getAccountName ( getPlayerAccount ( thePlayer ) ) if isObjectInACLGroup ("user."..accName, aclGetGroup ( "Policial" ) ) then if (state == "iniciar" or state == "finalizar") then name = getPlayerName (thePlayer) local horario = showTime() if (fileExists ("logPTR.txt")) then newFile = fileOpen ("logPTR.txt") fileSetPos (newFile, fileGetSize (newFile)) if (state == "iniciar") then outputChatBox ("Patrulha iniciada.", thePlayer) fileWrite (newFile, "["..horario.."] "name.." Iniciou sua patrulha.\n") -- linha do problema Este é meu script porém ele da este erro: config.lua:13 ')' expected near 'name'
  16. Bom eu tava conversando com um amigo meu, aele queria que eu lhe ajudasse fazendo um script de destruir carros porem eu n sabia, ele me mandou uma funcao feita pela comunidade e queria tirar algumas duvidas aqui. function destroyVehiclesOfModel(modelID) local vehicles = getElementsByType("vehicle") for i,v in ipairs(vehicles) do if (getElementModel(v) == modelID) then destroyElement(v) end end end Queria entender como funcionar esse for i,v in ipairs(vehicles) do Queria saber oque eh ipairs, do in e for, e suas funcionalidades se alguem puder explicar eu agradeco!
  17. Bom o LordHenry me ajudou fazendo um script que explicava o log de entrada e saida de determinado estados, iniciar PTR e finalizar PTR. Agora eu quero saber, como faço pra fazer contagem destas horas? No python existe funções para isso, tem como eu fazer também no MTA?
  18. Eu estava navegando entre os script's criado pela comunidade, e vi um que, você consegue por várias TXD em uma única DFF, eu achei muito bacana, pois reduz o peso de mods do servidor, porém acho que seria mais útil da seguinte forma: - Quando a pessoa passar por tal spawn, vai spawnar uma viatura com a DFF e com uma TXD X - Quando a pessoa passar por tal spawn y, vai spawnar uma viatura com a mesma DFF e com uma TXD Y(DIFERENTE DA OUTRA) E queria saber, acho que eu teria que criar uma elementData própria pra cada carro spawnado certo? Pensei em usar triggerClientEvent, porém muda todos os carros que estão no servidor e não apenas 1, oquê foi spawnado, taí a questão, alguém poderia me ajudar? Desde já agradeço!
  19. Muito Obrigado, Lord Henry, Antes disso não sabia fazer log's, a partir de hoje eu já sei! Você fez uma boa parte do script para mim, não precisava kkk, mas ajudou dms! Tmj mano Cara poderia me dar outra ajuda? Não entendo muito de orientador, quando que eu uso cmd, state? Poderia me explicar? Como posso fazer pra criar tabelas? Sempre fiz por elementData, e não sabia que pesava mais
  20. Nas regras do forum fala que niguém irá fazer um script de graça pra você, releia as regras, e faça outro tópico.
  21. Ducks, ninguém vai conseguir te ajudar, sem nem mesmo mostrar o script na qual você está tendo o problema... Recomendo que você reveja seu script, e tente fazer novamente.
  22. Olha, o getPlayerTeam, é só pra executar tais funções que você queira se ele tiver em tal grupo certo? Vamo supostamente, que você queira que só o Grupo A entre em tal área, você terá que setar a ele Grupo A. E na próxima função, vc usa o getPlayerTeam para ver se está no grupo, caso esteja, ele deixará entrar em tais bases.
  23. Bem, eu estava iniciando um script que se conceitua em ao player dar /ptr iniciar PTR e fazer algumas funções, até aí ok! Porém eu queria que fosse obrigatório ele finalizar, com outro comando, pra poder iniciar novamente, vamo supor, criar uma obrigatoriedade de ao iniciar ele ter que finalizar, pra dar novamente o comando de iniciar. Problema: Fazer uma função aonde não pode iniciar outra PTR sem ter finalizado outra. Conceito do Script: Euq ueria fazer como se fosse um "Log", para eu saber o tempo que as corporações fazem Patrulhamento em meu servidor. Se alguém puder me explicar como posso fazer isso com outro script... Desde já agradeço!
  24. Faça assim com base nessa função: function IniciarAssalto (Ped) Adicione isso: local Assaltante = getAccountName ( getPlayerAccount(source)) if isObjectInACLGroup ("user."..Assaltante, aclGetGroup ( "Assalto" ) ) then de forma que sua função fique deste jeito: function IniciarAssalto (Ped) local Assaltante = getAccountName ( getPlayerAccount ( source ) ) -- get his account name if isObjectInACLGroup ("user."..Assaltante, aclGetGroup ( "Assalto" ) ) then if Ped == PedLoja then local arma = getPedWeapon ( source ) if arma == 0 or arma == 1 or arma == 2 or arma == 3 or arma == 4 or arma == 5 or arma == 6 or arma == 7 or arma == 8 or arma == 9 or arma == 16 or arma == 17 or arma == 18 or arma == 39 or arma == 41 or arma == 42 or arma == 43 or arma == 10 or arma == 11 or arma == 12 or arma == 14 or arma == 15 or arma == 44 or arma == 45 or arma == 46 or arma == 40 then return end if getElementData(source, "TS:Assaltando") then return end if getElementData(Ped, "TS:Assaltando") then triggerClientEvent(source, "addNotification", root, "#0037FF✘#ffffffINFO#0037FF✘➺ #ffffffEssa loja foi assaltada recentemente!", "info") return end local x, y, z = getElementPosition( source ) local x1, y1, z1 = getElementPosition( Ped ) local distance = getDistanceBetweenPoints3D( x, y, z, x1, y1, z1 ) if distance >= 3 then return end triggerClientEvent(source, "TS:PainelAssalto2", source) end end end addEventHandler ("onPlayerTarget", root, IniciarAssalto) e da mesma forma você faz para o policial só que você irá fazer para esta função: function LojaAssaltada(source) setElementVisibleTo(BlipLoja, root, false) setElementVisibleTo(BlipLojaAssalta, root, true) setTimer(function() setElementVisibleTo(BlipLoja, root, true) setElementVisibleTo(BlipLojaAssalta, root, false) setElementData(PedLoja, "TS:Assaltando", false) end, 7*60000, 1 ) end
  25. Se você não informar o erro não vai ter como te ajudar Esse erro e comumente relacionado a elementData, que você deixou na HUD, veja no script da fome e sede o nome da elementData e conforme oquê mostra transcreva à hud.
×
×
  • Create New...