Jump to content

iPollo

Members
  • Posts

    26
  • Joined

  • Last visited

Everything posted by iPollo

  1. i'm experiencing lag running this code. Some one can help me to improve it or give me the hint to follow the best way to do it? in short the code does: it takes all elements in the determined range and checks if it is a collectable item, after that it adds the values of that item in a temporary table. When the player is next to the item (or items) the item's icon is drawn on it. Everything works ok, but the fps drops and it frozes slightly --========================================================================== -- Declarações --========================================================================== -- VAR: Booleanas local isPlayerCloseToItems = false -- VAR: Inteiros local playerCloseItemCount = 0 -- VAR: Tabela dos itens próximos local PLAYER_CLOSE_ITEMS = {} --========================================================================== -- Eventos --========================================================================== addEventHandler("onClientResourceStart", resourceRoot, function() lootCheckTimer = setTimer(lootCheck, 250, 0) print("cu") end) addEventHandler("onClientRender", root, function() if(isPlayerCloseToItems) then --dxDrawImageOnElement(0, 0, 3, texture, 10, -0.8, 1) for i = 1, playerCloseItemCount, 1 do for i = 1, 6, 1 do dxDrawItemIcon(PLAYER_CLOSE_ITEMS[i][3], PLAYER_CLOSE_ITEMS[i][4], PLAYER_CLOSE_ITEMS[i][5] - 1, PLAYER_CLOSE_ITEMS[i][6]) end end --dxDrawMaterialLine3D(0, 0, 2.7, 0, 0, 2.5, texture, 0.2, tocolor(255, 255, 255, 150)) end end) --========================================================================== -- Funções --========================================================================== function lootCheck() local x, y, z = getElementPosition(localPlayer) local closeElements = getElementsWithinRange(x, y, z, 10) local itemCount = 0 playerCloseItemCount = 0 isPlayerCloseToItems = false -- Limpar a tabela antiga count = #PLAYER_CLOSE_ITEMS for i=1, count do PLAYER_CLOSE_ITEMS[i]=nil end -- Pega o id dos itens próximos for key, value in pairs(closeElements) do if(getElementData(value, "isItem")) then print("CHAMADA INEXPERADA") playerCloseItemCount = playerCloseItemCount + 1 PLAYER_CLOSE_ITEMS[playerCloseItemCount] = {getElementData(value, "itemid"), getElementData(value, "itemName"), getElementData(value, "itemX"), getElementData(value, "itemY"), getElementData(value, "itemZ"), dxCreateTexture(getElementData(value, "itemIcon"))} end end if(playerCloseItemCount ~= 0) then isPlayerCloseToItems = true else isPlayerCloseToItems = false end for i = 1, playerCloseItemCount, 1 do for k = 1, 6, 1 do print(PLAYER_CLOSE_ITEMS[i][k]) end end end function dxDrawItemIcon(x, y, z, iconTexture) dxDrawMaterialLine3D(x, y, z + 2.7, x, y, z + 2.5, iconTexture, 0.2, tocolor(255, 255, 255, 150)) end
  2. Muito obrigado, ajudou muito EDIT: Surgiu outra dúvida, caso eu queira usar as funções de dentro da classe (métodos) em outro script, funcionaria normalmente exportando?
  3. Olá a todos, gostaria de saber como posso implementar os conceitos de OOP (caso seja possível) para o scripiting no MTA? Por exemplo: Caso eu queira criar uma classe ITEM, que tenha seus atributos e métodos, como eu poderia fazer isso em lua e aplicar no meu servidor? Um exemplo simples feito em java de como funcionaria a classe: public class Item { //Atributos que armazenarão a posição do item int item_POSX; int item_POSY; int item_POSZ; //Método que retornará a posição do meu item public int getItemPosX() return item_POSX; } Então por exemplo, caso eu queira adicionar um item e pegar a coordenada dele, em java ficaria assim: Item novoItem = new Item() novoItem.getItemPosX(); Claro que a estrutura que estou pensando envolve muito mais GETTERS e SETTERS coloquei simplificado apenas para exemplificar. Gostaria muito de saber como implementar isso no MTA usando LUA, também gostaria de saber, caso seja possível, se é recomendado utilizar OOP dessa forma em LUA para o MTA.
  4. Got it, but if i want to access a specific value, for example, the object id? how it should be? local objectid = items['medkit']....
  5. Okay, and about the table, I found an example of a table structure (below) local items = { ['apple'] = {desc = 'A green apple', name = 'apple', objectid = '2134'} } how should i do, using tabel.insert, to add a new item without doing it manually in the table itself, leaving it like this: local items = { ['apple'] = {desc = 'A green apple', name = 'apple', objectid = '2134'} ['medkit'] = {desc = 'A healing item', name = 'Medic Kit', objectid = '431'} } I know that initially it is like this: table.insert(items, 'medkit', ...) what should I put to fill in the fields within the 'medkit' index
  6. Hello everyone, I recently discovered that it is possible to place tables within tables, this would have saved me a lot of work a week ago ; -; but anyway. Currently, to save the items contained in the player's inventory I have a copy of unique tables on each side (server / client) and every time there is an update, I need to move the value from one side to the other, but this seems to be very strange, i know that the fundamental principle of events is this, but I think I am not doing it in the best way. For example, I currently have the player_INV table, with 10 index for access, which I access like this: player_INV [1] player_INV [2] so on. Each of these variables stores the inventory item ID or 0 if not. for this I'm doing a looping and using getAccountData and setAccountData to save, my question is this: "1) set and get AccountData is good for this type of saving, or should I do a specific query on a table for this?" "2) As I have a copy on each side, I could just create a global table in serverSide, using the player as an index, and within each index of the player, I place another table that contains the inventory slot? Cause i would only need to exchange the information once, as I would only perform the reading and writing on serverSide, through clientSide, since everything is stored there." I'm still a novice, so who can explain to me if it's possible and if it's, why it's the best method, I'd be grateful
  7. Hello everyone, I think I will still need to come here thousands of times to clear all doubts, so ... I have this function declared on serverSide function removeItemDoMundo(itemid) table.remove(spawnedItem_ID, itemid) table.remove(spawnedItem_NOME, itemid) table.remove(spawnedItem_X, itemid) table.remove(spawnedItem_Y, itemid) table.remove(spawnedItem_Z, itemid) table.remove(spawnedItem_ELEMENTO, itemid) removeWorldModel(spawnedItem_ID[itemid], 1.0, spawnedItem_X[itemid], spawnedItem_Y[itemid], spawnedItem_Z[itemid]) end I'm trying to call it on the clientSide, but give this error: "attempt to call globally removeItemDoMundo a nil value" Where I called, on clientSide: function addItemAoInventario(itemid, objetoid, slot) table.insert(player_INV, slot, objetoid) removeItemDoMundo(itemid) end But the strange thing is that, debugging the itemid value, before the function is called, it shows "1" that exactly the value I need, but for some reason it says it is null, I don't know why
  8. Hello, the first problem I am facing, is that in this function, there are no parameters that appear in the Wiki, it was supposed to have a height parameter, and two others (height and length of the image itself), but when I modify these values, only the width affects the image, because the height is related to the height of the drawing in relation to the element, so I cannot resize the image correctly. function dxDrawImageOnElement(TheElement,Image,distance,height,width,R,G,B,alpha) local x, y, z = getElementPosition(TheElement) local x2, y2, z2 = getElementPosition(localPlayer) local distance = distance or 20 local height = height or 1 local width = width 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 dxDrawMaterialLine3D(x, y, z+1+height-(distanceBetweenPoints/distance), x, y, z+height, Image, width-(distanceBetweenPoints/distance), tocolor(R or 255, G or 255, B or 255, alpha or 255)) end end end end On the wiki: Required arguments TheElement: The element you want to draw the image on it. Image: The image you want. Use dxCreateTexture to create it. Optional arguments height: The height of the text, it's 1 by default. distance: The distance you will be able to view the image from, it's 20 by default. height: The height of the image, it's 1 by default. width: The width of the image, it's 1 by default. it seems that there is no second image height parameter (third item of optional arguments), only the first one.
  9. I'm not sure if I understood, the point I want to get to, its find out which colShape is being hit by the player, see some examples: here is the function that will be called automatically, see that it creates the item, and a sphere around it: (serverSide) function createItemInMap(item, name, x, y, z) createObject(item, x, y, z) createColSphere(x, y, z, 1.5) end What I would like to know is how I do it, so when this event is called (onClientColShapeHit), on the clientSide, I automatically receive some "ID" from colShape, so I could know which item it is near, thus avoiding not necessary loopings addEventHandler("onClientColShapeHit", root, function(shapeID) --Then i check the item which belongs to this shapeID end)
  10. I understand, this way is much better, but let's assume that in my system, items are created automatically, so colShape will also be created automatically along with the items. In the example above, you specified which area the event will fire. As in my items will be created automatically on ServerSide, I can't go putting area by area, is there any way when the event is called on clientSide I receive some variable that contains the colShape id that was hitted?
  11. Yes, what I needed was as if it were an area, which then I would just check when the player's event entered a certain area was triggered, the problem with using onColShapeHit, is that it creates a physical collision area, and I I do not want it, cause the player would hit a "invisible shape" i do not know if colShape works like that way
  12. Hello everyone, I would like to ask the veterans a question. Let's suppose that I am making an item system, where when the player comes close to an item, the "F" key (in the form of an image) and the name of the item appear above it in a 3D way, this key is responsible for collecting items of the map. As dxDraw functions appear one time per frame, they must be included in the onClientRender/onClientPreRender to show all the time. Thinking about it, I thought of creating a loop through all the items that are on the map to be collected, and if the player is within the range of 1 meter for example of this item, he must display the image and name of the item, as mentioned above. The question arises now, creating a lopping within the onClientRender/onClientPreRender to do this verification would not generate a poor performance at GM?, as if it were a poorly optimized way, it would perform a looping and verification MANY TIMES, it would cause any lag or delay? Or I shouldn't even worry about it? I'm asking because I know languages and playing styles where it can't be done NEVER, it would cause tremendous underperformance at GM. EX: addEventHandler("onClientPreRender", root, function() for i = 1, table.size(spawnedItem_ID), 1 do local x, y, z = getElementPosition(localPlayer) if(getDistanceBetweenPoints3D(x, y, z, spawnedItem_X[i], spawnedItem_Y[i], spawnedItem_Z[i]) <= 5) then triggerEvent("onPlayerEnterItemArea", root, spawnedItem_ELEMENTO[i]) -- Draw the image and the text end end end)
  13. I do not know why, but its returning nil, is in a function whose other features work just fine, only that is not working local element element = createObject(item, x, y, z) outputDebugString("ELEMENT ID: "..getElementID(element)) DebugString: "INFO: ELEMENT ID: "
  14. Estudando, descobri que funções que desenham como dxDrawText aparece uma vez no frame e some, por isso deve ser colocada abaixo do onClientRender, que é acionado a cada frame novo, porém, como faço para habilitar e desabilitar em algum momento específico? Por exemplo: tenho um sistema de item, quando o jogador chega perto, desenha um texto na tela, quando se afasta, some, como devo fazer, para que funcione desta forma, pois diretamente abaixo do onClientRender ele iria aparecer o tempo todo.
  15. iPollo

    [Help] Events

    Okay, you literally opened my mind, now it's much clearer, and thanks for all the corrections. But for some reason it gives an error: attempt to call global 'client' <a user data value> on here: addEvent("onPlayerReady", true); addEventHandler("onPlayerReady", root, function() triggerClientEvent(client "onClientRecebeItemVar", root, item_ID, item_NOME, spawnedItem_ID, spawnedItem_NOME, spawnedItem_X, spawnedItem_Y, spawnedItem_Z) end)
  16. iPollo

    [Help] Events

    1) I didn't create it on ClientSide, because I thought that if it were "global" it would be accessible there. 2) Fixed And I made the other five points, but I still don't understand how to access array on the other side
  17. iPollo

    [Help] Events

    Hello everyone, I recently started with Lua programming at MTA, for studies, I started to develop a small system, whose goal is to create items on the map. So far everything worked perfectly, so I decided to implement an event, so that I know when the player goes through an item, but it didn't work (there are no errors in the console or in the debugscript) REMEMBERING: I started recently, so anything I have done wrong besides said, or that can be improved, let me know, please. For item creation I have this, at first, everything is working here, this is on ServerSide -- Count VARS local definirItem_Count = 0; local criarItemNoMapa_Count = 0; -- Table which stores the defined items item_ID = {} item_NOME = {} -- Table which stores spawned items on the map spawnedItem_ID = {} spawnedItem_NOME = {} spawnedItem_X = {} spawnedItem_Y = {} spawnedItem_Z = {} -- Function that defines the items function definirItem(item, nome) definirItem_Count = definirItem_Count + 1 table.insert(item_ID, definirItem_Count, item) table.insert(item_NOME, definirItem_Count, nome) end -- Function that creates the items on the map function criarItemNoMapa(item, nome, x, y, z) criarItemNoMapa_Count = criarItemNoMapa_Count + 1 createObject(item, x, y, z) table.insert(spawnedItem_ID, criarItemNoMapa_Count, item) table.insert(spawnedItem_NOME, criarItemNoMapa_Count, nome) table.insert(spawnedItem_X, criarItemNoMapa_Count, X) table.insert(spawnedItem_Y, criarItemNoMapa_Count, Y) table.insert(spawnedItem_Z, criarItemNoMapa_Count, Z) end -- Item definition definirItem(1853, "Chave de Fenda") definirItem(1577, "Mala Verde") definirItem(1580, "Mala Vemelha") definirItem(1579, "Mala Azul") I believe the problem arises in clientSide, because I have this -- Timer that repeats setTimer(verificarPositition, 500, 0) -- Function called by the timer to check if the player is in the range of an item -- For that I looped up to the highest value in the table of spawned items -- And I took the X, Y and Z values from certain tables -- And if the player is in this range, trigger the event function verificarPosition() for i = 0, table.maxn(spawnedItem_ID), 1 do local x, y, z = getElementPosition(getLocalPlayer()) if(isElementInRange(getLocalPlayer(), spawnedItem_X[i], spawnedItem_Y[i], spawnedItem_Z[i], 5)) triggerEvent("onPlayerEnterItemArea", getLocalPlayer()) end end end -- Event (its not been called) addEvent("onPlayerEnterItemArea", false) addEventHandler("onPlayerEnterItemArea", getRootElement(), function() outputChatBox("CALLED") end) Any help and improvement in the code will be a great help
  18. Qual a solução para adicionar o modelo novo? eu obrigatoriamente tenho que substituir algum do MTA?
  19. Esotu tentando importar um novo DFF e TXD, mas não estou conseguindo, pois da um WARNING, não sei como resolver: CÓDIGO (Client Side): addEventHandler("onClientResourceStart", getResourceRootElement(getThisResource()), function () -- Chave de Fenda txd = engineLoadTXD (":item/item_MODELS/ChaveDeFenda.txd", 18644) engineImportTXD (txd, 18644) dff = engineLoadDFF (":item/item_MODELS/ChaveDeFenda.dff", 18644) engineReplaceModel (dff, 18644) end) CÓDIGO (Server Side): itemID = 18644 addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), function () createObject(itemID, 0, 0, 2) end) WARNING: WARNING: item\item_CORE.Lua:11: Bad usage @ 'createObject' [Invalid model id] META: <meta> <script src="item_LOAD.Lua" type="client"/> <script src="item_CORE.Lua" type="server"/> <file src="item_MODELS/ChaveDeFenda.txd" type="client"/> <file src="item_MODELS/ChaveDeFenda.dff" type="client"/> </meta>
  20. Hello there, I'm trying to add an object to the map, so I imported a new DFF and TXD, but when I use createObject it returns a WARNING and it doesn't work.CODE (Client Side): CODE (Client Side): addEventHandler("onClientResourceStart", getResourceRootElement(getThisResource()), function () -- Chave de Fenda txd = engineLoadTXD (":item/item_MODELS/ChaveDeFenda.txd", 18644) engineImportTXD (txd, 18644) dff = engineLoadDFF (":item/item_MODELS/ChaveDeFenda.dff", 18644) engineReplaceModel (dff, 18644) end) CODE (Server Side): itemID = 18644 addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), function () createObject(itemID, 0, 0, 2) end) WARNING: WARNING: item\item_CORE.Lua:11: Bad usage @ 'createObject' [Invalid model id]
  21. Hello, a question that hit now, is it possible to use onClientGUIClick directly on an image created through the GUI (guiCreateStaticImage)? or do i need to create a button behind this image to be able to verify the click correctly? if that's how it works.
  22. Olá, uma dúvida que bateu agora, é possível utilizar o onClientGUIClick diretamente em uma imagem criada através da GUI (guiCreateStaticImage)? ou eu preciso criar um botão atrás dessa imagem para poder verificar corretamente o click? se é assim que funciona.
  23. iPollo

    [Help] Source

    Using this way you showed it worked, but it appears on the login screen, how can i put, to show at specific times, as if I had the ability to "hide" them and "show" them again
  24. iPollo

    [Help] Source

    Hello everyone, I started recently, so I'm really a layman, with very little knowledge in the MTA area, I'm triggering an event, and it seems to call correctly, but the dxDrawText functions are not being executed, nor the showCursor Function calling the event in another script triggerClientEvent(source,"onLogin",source) And here's the eventHandler in another script local screenW, screenH = guiGetScreenSize() addEventHandler("onLogin", getRootElement(), function() GUIEditor.pImg[1] = guiCreateStaticImage(0.32, 0.32, 0.19, 0.35, ":player/player_Sexo/IMG/IMG_Masculino.png", true) guiSetAlpha(GUIEditor.pImg[1], 0.85) GUIEditor.pImg[2] = guiCreateStaticImage(0.50, 0.32, 0.19, 0.35, ":player/player_Sexo/IMG/IMG_Feminino.png", true) guiSetAlpha(GUIEditor.pImg[2], 0.86) dxDrawText("MASCULINO", screenW * 0.3602, screenH * 0.3083, screenW * 0.4586, screenH * 0.3431, tocolor(255, 255, 255, 255), 1.00, "default", "center", "top", false, false, false, false, false) dxDrawText("FEMININO", screenW * 0.5406, screenH * 0.3083, screenW * 0.6391, screenH * 0.3431, tocolor(255, 255, 255, 255), 1.00, "default", "center", "top", false, false, false, false, false) showCursor(source) outputChatBox("FUNÇÃO CHAMADA") end )
  25. Entendi sim, muito obrigado.
×
×
  • Create New...