Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 24/01/19 in all areas

  1. سلام عليكم لي فتره معتزل من برمجه لكن رجعتتت بمود جديد و حصري مود عباره عن امر اسمه #send تكتب بالشات مثل كذا #send 100 100 عدد فلوس وبعدين مود نفسه يطلب منك علي طول تكتب اسم الاعب بالشات ( يجب عليك الان كتبت اسم الاعب ) يطلع لك بالشات كذا تكتب اسم الاعب عشان يوصلو له الفلوس وكل ذا داخل الشات وبنحط كود تحت طبعا هو يشتغل وكل شي لكن لو في غلط او شي او بق ياريت تقولو لي سيرفر addEventHandler("onPlayerChat",root,function(msg2) if getElementData(source,"go") == true then plr = getPlayerFromName(msg2) if plr then if plr ~= source then if getPlayerMoney(source) > 1 then givePlayerMoney(plr,tonumber(moeny)) givePlayerMoney(source,getPlayerMoney(source) - tonumber(moeny) ) outputChatBox(""..getPlayerName(source).." Has Been give moeny To "..getPlayerName(plr).." money is "..moeny.."",root,0,255,0,true) setElementData(source,"go",false) else outputChatBox("ليس لديك المال الكافي لارسله",source,255,0,0,true) setElementData(source,"go",false) outputChatBox("يجب عليك كتبت امر من جديد #send",source,255,0,0,true) end else outputChatBox("لا يمكن ارسل الفلوس لانفسك",source,255,0,0,true) setElementData(source,"go",false) outputChatBox("يجب عليك كتبت امر من جديد #send",source,255,0,0,true) end else outputChatBox("الاعب غير موجود بالسيرفر",source,255,0,0,true) setElementData(source,"go",false) outputChatBox("يجب عليك كتبت امر من جديد #send",source,255,0,0,true) end end end ) addEventHandler("onPlayerChat",root,function(msg) if string.find(msg,"#send") then if getElementData(source,"go") == false then len = string.len(""..msg.."") if len > 6 then text = string.sub(""..msg.."", 7,len) outputChatBox("يجب عليك الان كتبت اسم الاعب",source,0,255,0,true) setElementData(source,"go",true) moeny = text else outputChatBox("يجب عليك كتبت عدد الفلوس",root,255,0,0,true) end else outputChatBox("يجب عليك كتبت اسم الاعب لي ارسل الفلوس اليه",source,0,255,0,true) end end end ) الميتا <meta> <script src="server.lua" type="server" /> </meta> وفي مود ثاني قعد اشتغل عليه هو برنامج مثل لوحة ادمن بس لسه ما خلصته
    4 points
  2. O que é? Pra que serve? Um banco de dados é onde ficam salvos diversos tipos de dados que são usados entre as sessões dos jogadores e do servidor, isto significa que mesmo se o jogador relogar no servidor ou até mesmo o servidor reiniciar, os dados salvos no banco de dados não são perdidos. (se o script que salvou lá foi feito corretamente). O que posso salvar neles? O MTA já cria 2 bancos de dados padrão quando vc cria seu servidor, são eles: internal.db - Onde são salvos todos os dados das contas dos jogadores, login, senha, grana do bolso, posição do jogador quando deslogou, vida, colete, skin, armas, munição, etc. registry.db - Onde são salvos todos os dados que são utilizados pelos resources, como por exemplo melhores pontuações das corridas (race gamemode), proprietários das casas, dados bancários dos jogadores, saldo bancário dos jogadores, carros comprados pelos jogadores, roupas compradas pelos jogadores, empresas adquiridas pelos jogadores, etc. Onde eles estão? Estes dois bancos de dados estão na pasta deathmatch do seu servidor, estão na linguagem SQLite. Você ainda pode criar outros bancos de dados externos, para serem usados pelos resources, mas na minha opinião isso não é recomendável, uma vez que vc usaria MySQL, que é mais complexo e exige certos cuidados de acesso e domínio, mas alguns servidores profissionais precisam fazer assim pois fizeram os bancos de dados ficarem fora do servidor em outro IP por segurança, dai é necessário ter bancos de dados externos. Nesse tutorial vamos tratar somente dos bancos de dados nativos do MTA, por serem mais fáceis de entender. Como mexo neles? Para salvar alguma coisa na conta do jogador, isto é, no internal.db, você usa setAccountData, e para obter esses dados depois, use getAccountData. É extremamente simples, funciona da mesma forma que um setElementData, mas em vez de salvar uma data temporária em um elemento, salva uma data permanente numa conta. Porém, para salvar alguma coisa no registry.db, é um pouco mais complicado, uma vez que vc vai precisar criar uma tabela nova para cada resource. Por exemplo, vc acabou de criar um resource de ranking por kills/deaths e você deseja salvar esse ranking no banco de dados para que ao reiniciar o resource ou o servidor, o ranking não seja perdido. Para isso vc vai precisar primeiramente criar uma tabela no banco de dados registry.db, essa tabela será acessada pelo resource, que irá salvar os dados dele lá. Para fazer qualquer coisa neste banco de dados (criar tabelas, inserir, alterar, remover, deletar, inserir colunas em determinada tabela, etc) vc vai precisar usar isso: executeSQLQuery. Aqui, será necessário conhecimento em SQL para fazer isso, mas é mais fácil do que aprender uma linguagem de programação nova, pois suas opções e sintaxes são menores do que uma linguagem inteira de programação, você não vai inventar nenhum sistema novo aqui, apenas criar e gerenciar tabelas e dados. Criar tabela nova no banco de dados: (o Caps Lock não é uma regra, mas é melhor para entender o que é código e o que é nome) [Os seguintes códigos só funcionam server-side] executeSQLQuery ("CREATE TABLE IF NOT EXISTS nomedatabela (nomecoluna1 TEXT, nomecoluna2 REAL, nomecoluna3 INTEGER)") TEXT = Valores desta coluna serão textos. Podem ter símbolos, números e espaços. REAL = Valores desta coluna serão numéricos reais. (números decimais, positivos, negativos e 0.0) INTEGER = Valores desta coluna serão numéricos inteiros. (positivos, negativos e 0) (não existe tipo BOOLEAN, use TEXT e insira valor "false" ou "true") (existe valor NULL, é diferente de vazio e diferente de 0. NULL significa ausência de dados. O NULL aparece quando você cria uma linha ou coluna nova sem atribuir valores a elas.) Deletar tabela do banco de dados: executeSQLQuery ("DROP TABLE nomedatabela") Todas as linhas, colunas, células e valores desta tabela são deletados junto. Deletar linhas da tabela: (as células não ficarão NULL) executeSQLQuery ("DELETE FROM nomedatabela WHERE colunaespecífica=?", valorDaCelulaEspecifica) O ? indica que o valor está após a declaração do SQL. Você poderia colocar o valor direto no lugar do ?. Mas por alguma razão, as vezes isso gera erro. Além disso, se o valor da célula estiver em uma variável no seu script, você não pode declarar a variável no lugar do ?. Ali só pode ser o valor direto, pois a declaração SQL inteira se trata de uma string. Por isso o uso do ?, que está recebendo o valor da variável que está depois da vírgula. Obs: Para verificar se uma célula tem valor nulo, não se usa os operadores lógicos de ==, <= >=. Para isso, usa-se IS NULL ou IS NOT NULL. Ex: executeSQLQuery ("DELETE nomecoluna1,nomecoluna2 FROM nomedatabela WHERE nomecoluna3 IS NULL") Isso vai deletar todas as células da coluna 1 e coluna 2 onde a coluna 3 tem uma célula de valor NULL. Se a coluna 3 não tiver nenhuma célula de valor NULL, nada acontece. Inserir nova linha de valores: (ele vai criar automaticamente uma nova linha com novas células) executeSQLQuery ("INSERT INTO nomedatabela(nomecoluna1,nomecoluna2,nomecoluna3) VALUES(?,?,?)", valorCelulaColuna1, valorCelulaColuna2, valorCelulaColuna3) Neste caso, ele está inserindo 3 novos valores, cada valor em uma coluna. Se você não declarar os nomes das colunas, ele vai preencher na ordem das colunas automaticamente. Você pode deixar de declarar uma coluna se não quiser atribuir valor na célula daquela coluna. Se o tipo de valor da variável não for do tipo de dado daquela coluna, dará erro. Atualizar valores de células que já existem em uma tabela: (não é possível alterar os tipos de valores, é necessário editar o tipo da coluna se quiser fazer isso) executeSQLQuery ("UPDATE nomedatabela SET nomecoluna2=?,nomecoluna3=? WHERE nomecoluna1=?", valorCelulaColuna2, valorCelulaColuna3, valorCelulaColuna1) No caso acima, ele vai atualizar as células das colunas 2 e 3 onde o valor da célula da coluna 1 for igual ao valor de valorColunaCelula1. OBS: Nada impede que você coloque as primeiras variáveis junto à declaração SQL, mas para fazer isso você deve "cortar" a string, inserir as variáveis e depois continuar a string, Ex: executeSQLQuery ("UPDATE nomedatabela SET nomecoluna2= '".. valorCelulaColuna2 .."',nomecoluna3='".. valorCelulaColuna2 .."' WHERE nomecoluna1=?", valorCelulaColuna1) Lembrando que o valor destas variáveis também são strings na declaração, portanto use aspas simples antes e depois de cada corte para transformar os valores em string. Os dois pontos (..) significam que estes valores fazem parte do argumento SQL. Da mesma forma, se vc usar "1" .. "1", será igual a "11". (Por isso acho muito mais fácil deixar tudo ? na declaração SQL e colocar as variáveis todas após a string.) Selecionar determinadas células da tabela: (usado geralmente para obter os valores destas células para usar no script, você pode selecionar somente 1 célula ou várias) executeSQLQuery ("SELECT nomecoluna1,nomecoluna2 FROM nomedatabela WHERE nomecoluna3=?", valorCelulaColuna3) Neste exemplo, ele vai selecionar a célula da coluna 1 e a célula da coluna 2, na linha onde a célula da coluna 3 for igual a valorCelulaColuna3. Alterar a tabela (adicionar coluna nova) [SQLite não suporta deletar coluna nem editar tipo de coluna] executeSQLQuery ("ALTER TABLE nomedatabela ADD nomecoluna4 REAL") Devido a limitações do SQLite, ALTER TABLE não pode ser usado para deletar uma coluna nem para editar seu tipo. Para fazer isso é necessário recriar a tabela inteira com as novas alterações. No exemplo acima, ele vai adicionar uma nova coluna chamada "nomecoluna4". Tá, mas como ficaria tudo isso dentro de um script? Fiz um código com vários testes de banco de dados. Cada comando faz alguma coisa. É possível mexer em um banco de dados manualmente sem usar scripts? Sim, é possível. Eu mesmo costumo fazer isso para corrigir algumas coisas rápidas sem precisar programar mais nada. Para poder abrir os bancos de dados (internal.db e registry.db) você deve usar um programa chamado DB Browser for SQLite. Um programa gratuito, leve e bem fácil de entender. Nele você consegue acessar todas as tabelas do banco de dados e editar os valores como se fosse em uma planilha do Excel. Basta ir na aba Navegar dados, selecionar a tabela que deseja modificar, clicar em cima da célula cujo valor deseja atualizar, digitar o novo valor, clicar em Aplicar e depois clicar em Escrever modificações (salvar banco de dados). Pronto! E tem mais! Se você já tiver conhecimento avançado com a linguagem SQL, você também pode fazer alterações avançadas via código dentro do programa. Basta acessar a aba Executar SQL, escrever o comando SQL corretamente e depois clicar no botão de Play. Espero ter ajudado.
    1 point
  3. Olá pessoal. Fiz um vídeo bem detalhado sobre os painéis CEGUI, abordando algumas das principais dúvidas e também algumas propriedades que podem ajudar muito na hora de criar um painel GUI. Recomendo que assistam com fones de ouvido, ou então que ativem as legendas no YouTube. Críticas, sugestões, opiniões, perguntas relacionadas ao vídeo, podem fazer por aqui ou então deixar nos comentários do vídeo. (Deu muitíssimo trabalho de produzir o vídeo, deixe seu like neste post e no vídeo. Se puder, se inscreva no canal e acompanhe a página Lord Henry Entertainment no facebook.) Links e funções que aparecem no vídeo em ordem de aparição: http://static.cegui.org.uk/docs/0.8.7/ guiGetScreenSize guiCreateWindow guiCreateButton http://static.cegui.org.uk/static/WindowsLookProperties.html guiSetProperty http://static.cegui.org.uk/static/WindowsLookProperties.html#FrameWindow http://static.cegui.org.uk/static/WindowsLookProperties.html#Button isMouseOnGUICloseButton Standard_GUI_Font_Names guiSetEnabled guiSetAlpha guiEditSetReadOnly guiEditSetMasked Tenham todos uma boa semana.
    1 point
  4. Hello all! G&T Mapping here again, as usual at your service! Providing you with the latest high quality maps FOR FREE, made by us. Introduction: We're happy to anounce that the Public test version of our custom world 2.0 is now ready to download and test by the MTA community, i cannot emphasize enough that we need feedback from the community to make the best maps possible, so we ask of anyone that will try out the public test version to give us some feedback in return. We will keep up an active change log for all bug fixes and added features Map description: In addition to our first island we have added a second island so the map now consists of two separate islands where players are free to go and explore. (Check the change log for more info) New Addition to the Custom World! Gameplay footage! Important to note: We understand that these video's quality is mediocre at best, due to busted hardware we weren't able to record nor produce the videos with HD quality, though we decided to still release the content, regardless of the videos. Screenshots Second island: Screenshots First island: How to install *The world will be a separate map file including some resources, and all the textures. *Simly unpack the zip folder in your server's resource folder. *Turn on gtloader through the console or admin panel to auto-load all the models, and you're good to go. *If you want to run this map next to your exsisting free roam map you will have to load up both .map files. *The world will come with the default MTA deathmatch game mode. (We encourage testers to use their own game modes) Change log: (Second Island) #Added beaches. #Added Bridge. #Added boulevard. #Added industrial area. #Added suburban area. #Added shopping area. #Added airport. (General) #Added watermarks. *Fixed corner textures. Unresolved bugs: *From a aerial perspective you can clearly see object limit kicking in pretty hard, though this does not affect you on the ground levels. *Vehicles tend to load faster than the objects resulting in them falling beneath the floor. Feedback. All the feedback, suggestions and bug reports regarding the public test version may be submited in personal messages to myself or tails on the MTA forums. Please be clear about what kind of bug you're submiting, when you encountered it, and any posible solutions. Download Link: http://www.mediafire.com/download/k783p ... rld%5D.zip As always we will keep you posted on new changes, we've got a few nice things in store for you! ''soon'' G&T Mapping Needs You! Do you have any experience with recording videos in MTA, Mapping, Moddeling, or Scripting? feel free to send us a message so you too can join the G&T Mapping team! Thanks! G&T Mapping, Follow us on, Facebook: https://www.facebook.com/pages/GT-Mappi ... 213?ref=hl Our Blog: http://gtmapping.blogspot.nl/ We also still accept donations, press the donate button below!
    1 point
  5. Sometimes by just adding a random debug line in your code, it can reveal not updated code.
    1 point
  6. مود جميل , اهنيك بصراحة , و ولكم على رجوعك .
    1 point
  7. Problem fixed. For a weird reason one of the scripts wan't restarting and the changes weren't being applied. Anyways thanks for ur help. It was a f**** mistake by me. Around a f**** day looking for the error but now it is solved. Thanks and regards.
    1 point
  8. iprint(source) Did you debug it?
    1 point
  9. منور ياعسل , تسلم و ربي يحفضك
    1 point
  10. مود جميل من شخص اجمل موفق لك
    1 point
  11. Thank you very much. I get it now! It works!
    1 point
  12. لو حد حب اضيف شي في مود ي ريت يقول
    1 point
  13. جميل جدا تسلم علي الطرح
    1 point
  14. As it is now, the code triggers immediately while loading the resource and source is not defined.
    1 point
  15. آهنيك الصراحة سكريبت سهل ومييز ويساعد الناس وآصل آخي وننتظر الباقي منك تحياتي
    1 point
  16. Hmm, is your timing correct? (When is the second event being called) Is the eventName correct? Your test events are not correctly camelcase named, which might be correct named on serverside. ontest > onTest And how do you trigger?
    1 point
  17. Poxa, muito obrigado, me deu uma bela de uma ajuda mano, valeu de vdd!
    1 point
  18. Sim, é possível fazer com shader. Não tenho muito conhecimento com shader, mas sei que é um pouco complicado isso que você quer.
    1 point
  19. Use setElementModel na função 'donegobeach'. Você quer volte a última skin ou apenas setar outra? Se quiser setar a skin que o jogador estava, é só armazenar ela, com setElementData por exemplo. Também troque a função setPedSkin por setElementModel no evento "SkinDriver". Salvando a skin do jogador: addEvent("SkinDiver",true) addEventHandler("SkinDiver",root, function (skin) setElementData( source, "playerOriginalSkin", getElementModel(source), false ) setElementModel ( source, 45 ) end ) Setando na função 'donegobeach': function donegobeach ( thePlayer ) local TotalDiverjob = getElementData(thePlayer, "TotalpointDiverjob") or 0 local playerSkin = getElementData( thePlayer, "playerOriginalSkin" ) or 0 setElementData(thePlayer, "TotalpointDiverjob", TotalDiverjob + 1) setElementModel( thePlayer, playerSkin ) removeElementData( thePlayer, "playerOriginalSkin" ) givePlayerMoney ( thePlayer, 750 ) startJobDiver ( thePlayer ) outputChatBox("A sacola de dinheiro molhado foi aberta e você conseguiu recuperar $750,00.", thePlayer, 0, 255, 0) if ( isElement ( markergobeach ) ) then destroyElement ( markergobeach ) end if ( isElement ( BlipDiver ) ) then destroyElement ( BlipDiver ) end end
    1 point
  20. I rewrote the script by myself according to the BTTFHV team's server.
    1 point
  21. فاهم فكرة الفنكشن خطأ انت tonumber = يحول القيمة الموجودة الى رقم, مثلاً يحول السترنق الى رقم
    1 point
  22. الله يأخذ من أسس المنتدى .. ويأخذ مشرفين وأعضاء وعضوات المنتدى ....السلام عليكم ورحمة الله وبركاته ::لو أن السلام مو سنة كان ما سلمت ..!! قولوا ...آمــــــــــــييين الله ياخذ من أسس المنتدى ..ويآخذ مشرفين المنتدى...ويأخذ مشرفات المنتدى ...وياخذ أعضاء المنتدى ...ويآخذ عضوات المنتدى ...وياخذ زوار المنتدى ...وياخذ من يقرأ الموضوع ..وياخذني معاهم ..........:::: إلى ::::...........جنـــــــة عرضها السماوات والأرض ..لا هرم فيها ولا مرض لا تعب فيها ولا نصب ..لا هم فيها ولا وصب .. لا خوف فيها ولا هلعلا سأم فيها ولا جزع ......:: .. بعد عمـر طويـــــل مديــــد على الطاعة بإذن الله ..::.......آمــــــــــــــــــــيين ...
    1 point
  23. Make sure the two last arguments of the function are correct. You can test this code and show here the outputs on the chat: addCommandHandler("setvoice", function (command,sound1,sound2) if sound1 and sound2 then outputChatBox( "sound1: "..tostring(sound1) ) outputChatBox( "sound2: "..tostring(sound2) ) setPedVoice(getLocalPlayer(), sound1, sound2) end end )
    1 point
  24. APPENDIX DATA SYNCHRONIZATION. What is it? MTA's synchronization methods. Optimization tips. DATA SYNCHRONIZATION 1. What is it? Since unmemorable times humanity have faced problems caused mainly due to the storage of different ideas in almost each human. But thank God, machines storage methods are different and they have the possibility of having stored the same values in more than 100 machines. Well this is great, but those values must be set by someone, and here's where the server-side and client-side can be used as example of data synchronization. The server-side store's all the values given by each client-side and give's back those values to the all the client-sides ending up into something like this ( Figure 1 ). This is a way to get the same data in all the client-side, but there's also other methods well known like P2P. Figure 1. 2. MTA's synchronization methods. Since data sync it's a base element of every multiplayer game or mod, MTA is not an exception. That's why MTA scripting interface gives us two core ways to sync the server data with the client data or client data with server data. Well this two methods are the following one's. Element Data, it consists of assigning values to an element that are being stored under a key ( the key usually being a string like "health" ). This way is being used by a great amount of scripters in MTA because it's easy to use. But there are also negative points if this way is not being used properly like saving small amount of data in just one key and syncing it with the server or client's. An example of it would be: [[--CLIENT.LUA--]] local value = 0 local function handleStart() value = getTickCount() -- WE GET THE TIME THE SERVER HAS BEEN WORKING WHEN THE RESOURCE START setElementData( localPlayer, "start_tick", value, true ) -- WE SAVE THE 'value' VARIABLE INTO THE 'localPlayer' ELEMENT WITHIN THE KEY 'start_tick' AND WE SYNC IT TO GET THIS DATA TO THE SERVER. end addEventHandler( "onClientResourceStart", getResourceRootElement( getThisResource() ), handleStart ) [[--SERVER.LUA--]] local function handleCMD( thePlayer ) local mineTick = getElementData( thePlayer, "start_tick" ) -- WE RETRIEVE THE DATA, THAT HAS BEEN SAVED INTO 'thePlayer' DATA. local resultTick = getTickCount() - mineTick -- GET HOW MUCH TIME HAS PASSED SINCE THE RESOURCE STARTED FOR THE PLAYER outputChatBox( resultTick, thePlayer ) -- PRINT INTO THE CHAT THE RESULT end addCommandHandler( "mytime", handleCMD ) -- IN CASE YOU WANT TO TRY IT SAVE THE CODE WITH THE NAME MARKED ABOVE THEM. [[--META.XML--]] <meta> <script src="server.lua" type="server"/> <script src="client.lua" type="client"/> </meta> Events, this method is the one that elementData's one bases on, which means this is a 'rawer' method which can also be faster than elementData if it's being used efficiently. An event is just a message that's being send to one or various systems, if these systems handle the message then when the message is sent to the system there's a trigger which calls the functions that are defined like a reaction to that message that has been sent. It's pretty easy to understand, just think of this. You say hello to someone, the message in this case is 'Hello' and the system where is pointed to mainly is the person, the person gets the message and handles it by calling some cognitive functions, these functions at their time trigger another message as result which in the most common case would be 'Hello' or just a strange face motion because he or she doesn't know you. Maybe you will ask yourself about what does a hello to someone have to do with Events in MTA. Well let's convert the situation above into script. We've got to define first the message by using addEvent( "Hello" ), good we have defined our message, but if we stop here then we have made some useless stuff that's not going to be used ever, that's why we have to use this message somewhere and here is when we simulate the action of saying something the message by using triggerEvent( "Hello" ) but... wait who's supposed to say the message? Let's make it look like the localPlayer was saying the message so it would be like triggerEvent( "Hello", localPlayer ), okay we have said the message but do we talk alone? Maybe but it's not pretty normal, so we must find a receptor which in this case will be a ped so we add the a ped to the game by using createPed( 0, 105, 20, 5.5 ) supposing we are located in the position 104, 20, 5.5. Okay we have the receptor now but it won't answer to our message so let's obligate him to answer us by adding a handler for the message to the ped like this addEventHandler( "Hello", thePed ), okay but this way it will do the same as we wouldn't have used addEventHandler that's why we need to pass also a function to call like an argument which in this case is going to be called 'answerToHello' and we would finish up with addEventHandler( "Hello", thePed, answerToHello ). All this and little bit more of code below for simulating an answer to hello from a person in a non-realistic way. [[--CLIENT--]] -- EVENTS addEvent( "Hello", false ) -- LET'S MAKE IT LIKE JUST THE CLIENT CAN TRIGGER IT SO WE MAKE SURE JUST WE ARE GOING TO TALK TO THE PED -- VARIABLES local thePed = createPed( 0, 105, 20, 5.5 ) -- WE ADD THE PED SO WE DON'T FEEL LONELY -- FUNCTIONS -- SAY HELLO local function sayHello() -- THIS FUNCTION WILL BE USED TO SEND UP THE MESSAGE TO THE PED triggerEvent( "Hello", thePed ) -- WE SAY HELLO TO THE PED end -- ANSWER local function answerToHello() -- WE DEFINE THE MESSAGE HANDLER SO WE MAKE SURE THE PED ANSWERS TO US outputChatBox( "Hello to you too!" ) -- THE PED GET'S THE MESSAGE AND GIVES US BACK A MESSAGE THAT WE CAN CHECK INTO THE CHAT. end -- COMMANDS addCommandHandler( "sayit", sayHello ) -- WE'VE GOT TO SAY SOMEHOW HELLO TO THE PED SO LET'S USE A COMMAND -- EVENT HANDLERS addEventHandler( "Hello", thePed, answerToHello ) 3. Optimization tips. Well both methods can be used in large development but there are some tips you can follow to make sure your script will run in an efficient way. Pack reasonable amount of data into one's element data key, don't save values like ( health, armor, money ) into different keys, compress them into an only one by using tables, by using this method we pass 3 values packed in one sync meanwhile separating each value with one key creates upon 3 different syncs which would end up in a greater amount of packets sent between the server and the client. This tip can be used for both methods [ elementData, Events ]. local basic_data = { health = 100, armor = 100, money = 100 } -- COMPRESSED PLAYER INFO setElementData( thePlayer, "main", basic_data, true ) -- WE GIVE 3 DIFFERENT VALUES TO 'main' KEY BY USING JUST A VARIABLE THAT'S A TABLE 'basic_data' triggerClientEvent( thePlayer, "onSync", thePlayer, basic_data ) -- WE SEND A MESSAGE TO THE CLIENT IN ORDER TO MAKE IT SYNC THE DATA OF THE PLAYER TO THE ONE THAT IS BEING STORED IN THE SERVER Lua is a garbage collection language so the reduce the amount of global variables as much as possible in order to make it run faster. Hope you enjoyed the tutorial, if you have any question just feel free to ask it in this post or by PM, Skype ( killer.68x ) or Email ( [email protected] ) or Discord ( Simple01#1106 ).
    1 point
  25. Yep @LopSided_, re-read it already, and found that I misread his comment.
    1 point
  26. local vehicle = getPedOccupiedVehicle(source) local x,y,z = getElementPosition(vehicle) local _,_,rz = getElementRotation(vehicle) x = 10 * math.cos(math.rad(rz+90)) + x y = 10 * math.sin(math.rad(rz+90)) + y markers[source] = createMarker(x,y,z-1,'cylinder',4,255,255,255,255)
    1 point
  27. EDITADO Ola, hoje tentarei explicar um pouco sobre a funcão math.random. O que ela faz? R: ela sorteia um numero aleatório. exemplo: function MinhaFuncao(thePlayer) local Numero = math.random(1,2) if (Numero == 1) then givePlayerMoney(thePlayer,200) outputChatBox("Você acerto",thePlayer) else killPed(thePlayer) outputChatBox("Você Errou por isso sera morto!",thePlayer) end end addCommandHandler("sorte",MinhaFuncao) Neste Exemplo quando um jogador digitar /sorte sera gerado uma matematica aleatoria (math.random) dos numeros 1 até 2 ou seja 1 ou 2. Em seguida armazenamos esse valor na variavel Numero. Então checamos se o numero gerado é 1, se for o jogador (thePlayer) ganhara R$ 200,00 e uma mensagem sera iniciada dizendo que ele acertou! Caso contrario (else) ele sera morto. Funções usadas: givePlayerMoney adiciona dinheiro a um jogador o 1° argumento é o jogador que você quer dar dinheiro. o 2° argumento é a quantidade ( quantos de dinheiro ele vai ganhar?) outputChatBox Cria uma mensagem no chat. o 1° argumento é a mensagem. o 2° é (opcional) é para quem você vai mandar a mensagem. o 3° é (opcional) que representa a quantidade de cor vermelha que a mensagem tera. o 4° é (opcional) que representa a quantidade de cor verde que a mensagem tera. o 5° é (opcional) que representa a quantidade de cor azul que a mensagem tera. killPed mata um ped/player o 1° argumento se refere a quem sera morto! Bom pessoal foi isso. Qualquer duvida/sugestão/critica fique a vontade para postar. Obrigado! local numeros = { "Um", "Dois", "Três", "Quatro", "Cinco", "Seis", "Sete", "Oito", "Nove", "Dez" } outputChatBox( numeros[math.random(1, #numeros)] ) nesse exemplo que o dnl291 criou, vou tentar explicar algumas coisas (me corrija se tiver errado sou novo com tabelas) Então primeiro é criado uma tabela (numeros) então é adicionado uma caixa de xat para exibir o resultado aleatorio. Então você se pergunta: como vou tirar um numero aleatorio de uma tabela? então é como se cada elemento da tabela correspondesse a um numero. então numeros[1] = "Um" numeros[2] = "Dois" e assim sucessivamente. numeros[1] é o primeiro elemento da tabela numeros. De um jeito logico na math.random é enumerado cada item da tabela e cada item é um numero. Voltando ao script: para que usar o #? R: esse simbolo é usado para obter o comprimento de uma tabela ou string. Como Crio uma tabela? R: você inicia uma tabela com "{" e termina com "}" Um pequeno exemplo: (apenas exemplo) local Semana = {"Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sábado"} function SemanaFuncao() local S = Semana[math.random(1,#Semana)] if (S == "Sábado") or (S == "Domingo") then outputChatBox("Hoje é final de semana, curta seu tempo livre") else outputChatBox("Hoje é dia de trabalhar, o que você esta esperando para começar? um convite?") end end addCommandHandler("Semana",SemanaFuncao) Novamente agradeço a quem leu esse topico, obrigado dnl291 pela sugestão (e correções)!
    1 point
  28. Please Serial Banned remove Im Serial Banned: BF0383801BAD8A1E68281BD78540BD52
    0 points
×
×
  • Create New...