Leaderboard

  1. The_GTA

    The_GTA

    Members


    • Points

      32

    • Content Count

      285


  2. Lord Henry

    Lord Henry

    Other Languages Moderators


    • Points

      15

    • Content Count

      2,945


  3. IIYAMA

    IIYAMA

    Scripting Moderators


    • Points

      15

    • Content Count

      5,174


  4. ^iiEcoo'x_)

    ^iiEcoo'x_)

    Members


    • Points

      13

    • Content Count

      2,891



Popular Content

Showing content with the highest reputation since 29/03/20 in all areas

  1. 4 points
    Hey people, how is prison? 💣 In 2015 I released a beta version of a resource that created driving trains. But unfortunately I never finished it. So that is why I am making a final update for it, including rewriting and cleaning the old code. The this version will be uncompiled, so you can adjust it like you want. It will take some more days to finish it, so be patient. I can send you a pre-version, if you like to try it out before the release. No requirements for a pre-version, just a little bit feedback would be nice. To receive the pre-version, send me a personal message and I will send you the version within 1-3 days. The old topic:
  2. 3 points
    I will somewhere this week publish a new version of this resource. Because I wanted to finish it at-least. Uncompiled Better optimised than previous versions. CPU (3,5-3,9 GHz) 4 trains +/- 1.22% usage 40 trains +/- 7.05% usage Overkill Cleaned up a lot of the old code (I wrote this in 2015.. , never the less it is still ugly :C) Added some custom train-cart designs. Fixed all known bugs. Trains won't stop, even in this version. But you can try to make that yourself... If you want to test it out, before I put it on the community, free feel to send me a message. But in return I did like to receive some feedback.
  3. 2 points
    Opa, desculpe, eu lhe informo o erro sim, o erro estava na seguinte linha : if (source == binco1m and getElementType(player) == "player") then Está certo, mas, o que esta de errado ai? Nesse caso, o source é o marker que você atingiu, certo? Então nesse caso, está tentando fazendo o seguinte : if (source == binco1m) then --# "source" o MARKER que você colidiu. --# "binco1m" o MARKER que você quer colidir. --# Então essa verificação, vai verificar se o marker que você quer colidir, é o que você colidiu. Só que o seguinte, o marker que você denominou na criação do seu marker foi "bincoB". bincoB = createMarker(217.5, -98, 1006, "arrow", 1.5, 255, 0, 0) Então, você precisaria trocar o nome na verificação de "binco1m" para "bincoB" na sua verificação, assim : if (source == bincoB and getElementType(player) == "player") then Entende? Espero que sim, o erro só foi esse aparentemente.
  4. 2 points
    O script está em server-side, mude pra client-side.
  5. 2 points
    local functions = { outputText = function ( ... ) outputChatBox ( ... ) end, } functions.outputText ( "Hello", root, 255, 255, 255, true )
  6. 2 points
    Project trains <information removed - full information will be added in the month April 2020> This resource will create trains across the map and make them drive automatic. It makes San Andreas a little bit more alive. Version 1.0.0 Serverside time synced trains for multiplayer Version 2.0.0 Uncompiled Better optimised than previous versions. CPU (3,5-3,9 GHz) 4 trains +/- 1.22% usage 40 trains +/- 7.05% usage Overkill Cleaned up a lot of the old code (I wrote this in 2015.. , never the less it is still ugly :C) Added some custom train-cart designs. Fixed all known bugs. Trains won't stop, even in this version. But you can try to make that yourself... Improved bandwidth <link removed, new link will be available soon>
  7. 2 points
    Já começou errado querendo um gerador de script. Faça na raça mesmo, aumentando os valores e testando.
  8. 2 points
    I made a video to show how its working, Im not sure if is the same effect you trying to do the part the changes the position while resizing is something like: addEventHandler("onClientGUIScroll", root, function(element) setObjectScale(roda,guiScrollBarGetScrollPosition(element)/10) attachElements(roda,getPedOccupiedVehicle(localPlayer),rodax,roday,rodaz+getElementDistanceFromCentreOfMassToBaseOfModel(roda)*getObjectScale(roda)-getElementDistanceFromCentreOfMassToBaseOfModel(roda)) end) with roda being the wheel object and rodax,roday,rodaz the attachelements offsets, to make the wheel object rotate with the real wheel I made a onclienprerender event getting the car z rotation and the wheel rotations: function rodarot() local vrotx,vroty,vrotz=getElementRotation(getPedOccupiedVehicle(localPlayer)) local rodarx,rodary,rodarz=getVehicleComponentRotation(getPedOccupiedVehicle(localPlayer),"wheel_rf_dummy") setElementRotation(roda,rodarx,rodary,rodarz+vrotz) end this code is not optimized nor checking for warnings/errors, just an example for use in a proper code
  9. 2 points
    السلام عليكم ورحمة الله وبركاته كثير أشوف ناس نفسها تتعلم برمجة و إلخ , ف ببدأ بدورة تعليم إن شاء الله .. إسم الدورة : عبادي كورس .. على بركة الله : لازم تعرف أشياء أساسية باللغة بشكل عام : [1] - function [2] - if [3] - then [4] - end - function : تستخدم لإنشاء وظيفة , شو هي الوظيفة أصلاً ؟ , كثير ما نلاحظ وظائف موجودة أساسيا باللعبة مثل : setElementData , setPlayerArmor , isPedDead مثلا الأولى تُستخدم لإعطاء لاعب داتا , والثانية لإعطاء لاعب درع , و الثانية لمعرفة اللاعب ميت أو لا .. هذي كلها تسمى وظائف ( فنكشن ) ء تم إنشاء هذه الوظائف ( function ) من خلال ال توضيح أكثر ؟ function setPlayerArmor هكذا تم إنشاء الوظيفة الي نشوفها فوق ^ , طيب هسا نجي نفكر بالمنطق , وظيفة تعطي درع للاعب ؟ طب مين اللاعب الي بدي اعطيه , هل رح اعطي نفسي , ولا اعطي لاعب عشوائي ! تسويها من الفنكشن نفسه , طب كيف ؟ arguments نحط بين قوسين كلمة تدل على اللاعب الي بدي اعطيه , ونسميها هذي الكلمة . - اهم شيء تكون بين قوسين , زيادة قوس او تنقيص قوس = خطا function setPlayerArmor ( player ) -? player طب عندي سؤال هسا , شرط احط كلمة - لا مو شرط , أي كلمة تدلك ع اللاعب الي رح تعطيه مستقبلاً , مثال : function setPlayerArmor ( p ) function setPlayerArmor ( x ) function setPlayerArmor ( z ) - ! arguments طب انا ما فهمت كلمة هسا بقولك كيف تفهمها , انا بدي اعطي لاعب محدد درع , رحت اخترت لاعب من القائمة عشان اعطيه درع , يدلني على اللاعب argument يدلني على اللاعب الي بدي اعطيه , اذا لازم الوظيفة يكون فيها argument رحت ع الوظيفة , ما فيها نجي نفكر هسا , طب انا حددت اللاعب الي بدي اعطيه الدرع , بس كم كمية الدرع الي بدي اعطيه اياها !!! - مثلا انا بدي اعطيه نص درع ( 50 ) بالمئة .. جديد خاص بكمية الدرع argument إذا لازم نسوي function setPlayerArmor ( x , armor ) جديد argument وهيك سوينا argument لازم نحط فاصلة بين كل . - argument ملاحظات بسيطة : لازم فاصلة بين كل - إسم خاص فيه , ممنوع تكرر الإسم argument لكل طبعاً هذي أساسيات , نراكم ب الجزء 2 ,, راجعو الجزء 1 مرتين وافهموه و احفظوهـ , اي اسئلة على الخاص ~ - المحترفين بالبرمجةة : عارف انه لسا مو مكمله , بس اهم شيء التاسيس ~~ * ملاحظة : لمعرفة قراءة الموضوع ، اذا كنت من التلفون حط وضعية سطح مكتب ، الافضل تقراها من اللابتوب او الكمبيوتر .. إختبار : [1] - أي الآتي خاطئ : A- function newfunction ( n ) B- function NewFunction ( z , c , s ) C- function Newfunction ( n ; F ) [2] - صحح الخطأ : A- function nEwFunction ( sop ,, o ) B- function newfunction n , b C- function news ( n , n ) D- function ( newFunction , n )
  10. 2 points
    Haha, no no! That is not what you should do Let me explain. Inside the client events you should do what you previously did inside of the vehicle_left, vehicle_right key handlers! This is how your vehicle indicator scripts is executed on every game client on the server if one of them steers the vehicle left or right. Then you have to use triggerServerEvent inside of the vehicle_left and vehicle_right key handlers to send either onVehicleTurnOnIndicator or onVehicleTurnOffIndicator events, depending on if the key is pressed down or not. Imagine it like this: So try moving around the code on the client-side. What is now inside the key handlers should be put into the onClientVehicleTurnOn/OffIndicator event handlers. Then add new code into the bind key handlers to call the server events.
  11. 2 points
    function lockCar(player, cmd) local radius = 3 local x, y, z = getElementPosition(player) local vehiclesAround = getElementsWithinRange(x, y, z, radius, "vehicle") local vehicleElement = false if #vehiclesAround == 0 then outputChatBox("no vehicles around", player, 220, 220, 0) return end for i = 1, #vehiclesAround do vehicleElement = vehiclesAround[i] if getElementData(vehicleElement, "uid") and getElementData(vehicleElement, "uid") == 0 then setVehicleLocked(vehicleElement, true) outputChatBox("lock", player, 220, 220, 0) break end end end addCommandHandler("wv", lockCar) Here you go, i also changed loop to faster, and we don't need colshape to get vehicles around. (+problem is that, that you create colshape and never delete it)
  12. 1 point
    Hey, For several weeks I have a lot of problems with lag on our server when it is full (700-800 players). I have made every effort to get rid of the problem. Unfortunately, the server situation has still not changed. The problem is I don't know what I can do to improve the situation. Statistics (server info in perfomance browser) dont show server overload. Below are some sample screenshots of server info. server specification: CPU: Intel Xeon-E 2288G (4.8GHz Turbo Boost) Bandwidth: 1 Gb/s Memory: 64 GB RAM SSD NVMe In addition, we encounter major synchronization problems (which leads to bugs). For some players, the vehicle stands in one place for several minutes, while in others it drives and synchronizes on a regular basis. The player entering (or onto) the vehicle he is standing at can teleport. Examples in the spoiler. Thank you in advance for your reply and help.
  13. 1 point
    Você me enviou MP, mas, responderei aqui também ! Opa, tem sim ! função se chama setWeaponProperty. Ex: setWeaponProperty("m4", "pro", "weapon_range", 50.0) setWeaponProperty("m4", "std", "weapon_range", 50.0) setWeaponProperty("m4", "poor", "weapon_range", 50.0)
  14. 1 point
    We all know that this is a result of something being unoptimized in your server, but please tell us what it was so that other scripters can see a practical example of script abuse that results in high RakNet thread usage like this. Especially the interested ones that have been following conversations on the MTA Discord in which we tried to help you troubleshoot. Also, please mention how you fixed the problem or how you optimized it.
  15. 1 point
    Teste : local GUIEditor = { button = {}, gridlist = {}, } function BuySkin() --/> Criar Marker & Ped bincoB = createMarker(217.5, -98, 1006, "arrow", 1.5, 255, 0, 0) setElementInterior(bincoB, 15) vendedora = createPed(12, 209, -99, 1005, 180) setElementInterior(vendedora, 15) addEventHandler("onClientMarkerHit", bincoB, ShowSkins) --/> Movido --/> Painel GUI Painel = guiCreateWindow(838, 320, 375, 331, "PAGUE MENOS", false) guiWindowSetSizable(Painel, false) guiSetAlpha(Painel, 0.92) guiSetProperty(Painel, "CaptionColour", "FFFEEB16") guiSetVisible(Painel, false) sair = guiCreateButton(269, 288, 92, 33, "Sair", false, Painel) guiSetProperty(sair, "NormalTextColour", "FF39EB3D") GUIEditor.button[4] = guiCreateButton(9, 288, 97, 33, "Comprar", false, Painel) guiSetProperty(GUIEditor.button[4], "NormalTextColour", "FF39EB3D") addEventHandler("onClientGUIClick", sair, exibir) --/> Movido GUIEditor.gridlist[3] = guiCreateGridList(9, 27, 352, 257, false, Painel) guiGridListAddColumn(GUIEditor.gridlist[3], "Skins", 0.3) guiGridListAddColumn(GUIEditor.gridlist[3], "ID", 0.3) guiGridListAddColumn(GUIEditor.gridlist[3], "Preço", 0.3) for i = 1, 2 do guiGridListAddRow(GUIEditor.gridlist[3]) end guiGridListSetItemText(GUIEditor.gridlist[3], 0, 1, "skin1", false, false) guiGridListSetItemText(GUIEditor.gridlist[3], 0, 2, "-", false, false) guiGridListSetItemText(GUIEditor.gridlist[3], 0, 3, "-", false, false) guiGridListSetItemText(GUIEditor.gridlist[3], 1, 1, "-", false, false) guiGridListSetItemText(GUIEditor.gridlist[3], 1, 2, "-", false, false) guiGridListSetItemText(GUIEditor.gridlist[3], 1, 3, "-", false, false) end addEventHandler("onClientResourceStart", resourceRoot, BuySkin) function ShowSkins ( player, Dimensao ) if isElement(player) and getElementType(player) == "player" then exibir( ) end end function exibir ( ) guiSetVisible(Painel, not guiGetVisible(Painel)) showCursor(guiGetVisible(Painel)) end
  16. 1 point
    @Renaz Você não declarou o lado do script no meta.xml
  17. 1 point
    <meta> <script src="client.Lua" type="client" /> <script src="sever.Lua" type="server" /> </meta> irmão tenta por assim
  18. 1 point
    https://wiki.multitheftauto.com/wiki/CEF_Tutorial
  19. 1 point
    This happens because your internet may be overused if you're downloading or interacting with the internet by any manner just stop or if you're sharing your internet with someone else just ask them to pause their activity for a moment.
  20. 1 point
    I think the message is confusing. The timer just waits 2 seconds and not 5 minutes. I doubt that you are typing "/rp" two times faster than 2 seconds. But the script above does prevent ... "rapid" enabling. And then there is this weirdness about a timer inside of a timer. Maybe try increasing some timers?
  21. 1 point
    هذا جدول ماله أي علاقه, شوف نفس الطريقة اللي سويتها فوق, حط الرقم او المتغير بدل الرقم اللي حطيته أنا أو هات كودك.
  22. 1 point
    I hope you think chat and not cheat Something like that. (its not the full code, you need to finish it!) -- SERVER function sendMessageToCustomChat(player, cmd, ...) -- TODO: check if `player` can use this command local text = table.concat({...}, " ") for i, target in ipairs(getElementsByType("player")) do -- TODO: check if `target` can see this message outputChatBox(text, target) end end addCommandHandler("chatcommand", sendMessageToCustomChat)
  23. 1 point
    Hint: you can calculate 1/2 plus the half of cosinus of a time-fraction multiplied by 2PI to get a wave-function between 0 and 1; by setting this value to the intensity shader variable you will get a "smooth" animation.
  24. 1 point
    In the future can you please use the Spanish section for non-English posting. This does not include the current thread as we'll move it there. https://forum.mtasa.com/forum/166-spanish-español/
  25. 1 point
  26. 1 point
    Ohh, i think i understand but not 100% from this 😂 Server: addEvent("onVehicleTurnOnIndicator", true); addEventHandler("onVehicleTurnOnIndicator", root, function(right_indicator) local vehicle = getPedOccupiedVehicle (client) if vehicle then triggerClientEvent ( "onClientVehicleTurnOnIndicator", vehicle, right_indicator) end end ); addEvent("onVehicleTurnOffIndicator", true); addEventHandler("onVehicleTurnOffIndicator", root, function(right_indicator) local vehicle = getPedOccupiedVehicle (client) if vehicle then triggerClientEvent ( "onClientVehicleTurnOffIndicator", vehicle, right_indicator) end end ); Client(key handler): local function vehicle_right_down() triggerServerEvent("onVehicleTurnOnIndicator", root,right_indicator) end bindKey("mouse2", "down", vehicle_right_down) local function vehicle_right_up() triggerServerEvent("onVehicleTurnOffIndicator", root,right_indicator) end bindKey("mouse2", "up", vehicle_right_up) Client(event): addEvent("onClientVehicleTurnOnIndicator", true); addEventHandler("onClientVehicleTurnOnIndicator", root, function(right_indicator) indicator_right_on = true; indicator_right_start = getTickCount(); end ); addEvent("onClientVehicleTurnOffIndicator", true); addEventHandler("onClientVehicleTurnOffIndicator", root, function(right_indicator) dxSetShaderValue(shader_right, "intensity", 0); indicator_right_on = false; end ); Buuuuut, it is not working, so i failed again 😅
  27. 1 point
    Hello FIY9AL, I think this is a working function, cool! What you could improve though is setting the internal fadeIn function to be a local function, like this: local function fadeIn() fadeCamera(player, true, fadeinTime, 0, 0, 0) end Then the function does not leak to the global namespace. If we were to discuss the user friendliness, I could argue that you'd reorder function arguments so that player is the first argument and then default the waitTime and fadeinTime argument to be the same as fadeoutTime (of course multiply waitTime by 1000 to get ms time). This is because then you could simply write: eyeBlink(player, 0.5)
  28. 1 point
  29. 1 point
    guiGetScreenSize interpolateBetween getTickCount dxDrawImage addEventHandler - 'onClientRender'
  30. 1 point
    i will try to figure out how to do a new command to update in the server side, and try to share the information with the saving script that i have, Thank you so much by your help, God Bless you, and if i have any problem running the code i will notify here ❤️
  31. 1 point
    I have not looked into the script much but you have to know who is eligible for the special wheels and then store that in a table on the server. Then also store what wheels they picked. I mentioned the event functions before. It really is not easy to get into, especially since that script is so huge and honestly not very well documented. I don't think that the difficulty is in the Lua language, but rather the questionable design of the code that you are dealing with.
  32. 1 point
    It's simpler for weapons like Uzi, there will be dual-wield with the weapon skill maxed. Example: function doubleUzi() setPedStat(source, 75, 999) end addEventHandler("onPlayerJoin", getRootElement(), doubleUzi)
  33. 1 point
    man, now my head is broken 🤔, as i said in the start i only know the very basics like show a message in the screen , i will really need help in that. but, how can i share the donation information across clients, and trigger a server event?. for you can be easy to solve but for me it is an alian language 😅 i don't want to abuse of your generosity, so if u are busy or can't help i will understand and try to learn and solve myself, it will take a loooooong time but i think it will work i guess 😅 😅
  34. 1 point
    No problem! I hope that you get it sorted out. Hopefully you were not scammed by some guy who promised you a feature. If you want scripting advice for implementing it yourself feel free to ask in this thread. Then I will guide you.
  35. 1 point
    Hello iwalidza, if you want to have the camera move around in a circle around a point then you can simply use the math.sin and math.cos functions of Lua in combination with MTA's setCameraMatrix function local cam_move_start = getTickCount(); local cam_radius = 50; local cam_move_circle_duration = 15000; local cam_move_angle_start = 0; local cam_movearound_point_x = 0; local cam_movearound_point_y = 0; local cam_movearound_point_z = 0; local cam_height_offset = 20; local function get_camera_point_circular() local now = getTickCount(); local passed_time = now - cam_move_start; local progress_circle = passed_time / cam_move_circle_duration; local cam_current_angle = math.rad(cam_move_angle_start + progress_circle * 360); local cam_pos_x = cam_movearound_point_x + cam_radius * math.cos(cam_current_angle); local cam_pos_y = cam_movearound_point_y + cam_radius * math.sin(cam_current_angle); return cam_pos_x, cam_pos_y, cam_pos_z + cam_height_offset; end addEventHandler("onClientPreRender", root, function() local cam_pos_x, cam_pos_y, cam_pos_z = get_camera_point_circular(); setCameraMatrix(cam_pos_x, cam_pos_y, cam_pos_z, cam_movearound_point_x, cam_movearound_point_y, cam_movearound_point_z); end ); (code has not been tested) The math.cos and math.sin functions are used to model a circle in math. You should learn about those in your school math classes. Extended knowledge can be gained in University which I highly recommend to attend to! - Martin
  36. 1 point
    veh = {} -- Table de veículos, cada veículo será indexado em determinado jogador. addCommandHandler ("carro", function (thePlayer, cmd) if (veh[thePlayer]) then -- Se o veículo do jogador já existe, então: destroyElement (veh[thePlayer]) -- Destrói o veículo. veh[thePlayer] = nil -- Remove o veículo da table. outputChatBox ("Seu carro VIP foi destruído.", thePlayer, 255, 255, 0) else -- Se o veículo não existe, então: local x, y, z = getElementPosition (thePlayer) veh[thePlayer] = createVehicle (602, x, y+3, z+1) -- Cria o veículo, próximo ao jogador. setVehicleColor (veh[thePlayer], 0, 0, 0) -- Torna o veículo preto. setElementData (veh[thePlayer], "owner", getAccountName (getPlayerAccount (thePlayer))) -- Coloca o login de quem criou o veículo como dono. outputChatBox ("Carro VIP criado.", thePlayer, 0, 255, 0) end end) addEventHandler ("onVehicleStartEnter", root, function (thePlayer, seat, jacked) -- Quando alguém tenta entrar em um veículo, ativa essa função. if (getElementModel (source) == 602) then -- Se o veículo que o jogador está tentando entrar for o modelo do carro VIP, então: if (isGuestAccount (getPlayerAccount(thePlayer))) then return cancelEvent() end -- Se o jogador estiver deslogado, nada acontece e ele nem entra no veículo. (a ação de entrada no veículo é cancelada) if (seat == 0) then -- Se o jogador está tentando entrar como motorista, então: if (not isObjectInACLGroup ("user."..getAccountName(getPlayerAccount(thePlayer)), aclGetGroup ("VIPCARRO"))) then -- Se o jogador que está tentando entrar não estiver na ACL Group VIPCARRO, então: outputChatBox ("Você não tem permissão para dirigir veículos VIP.", thePlayer, 255, 0, 0) cancelEvent () -- Cancela a entrada no veículo. elseif (getElementData (source, "owner")) then -- Se o jogador está na ACL Group VIPCARRO e o carro tem um dono registrado, então: if not (getElementData (source, "owner") == getAccountName(getPlayerAccount(thePlayer))) then -- Se o jogador que está tentando entrar não for o dono do veículo, então: outputChatBox ("Você não pode dirigir este veículo pois ele não pertence a você.", thePlayer, 255, 0, 0) cancelEvent () -- Cancela a entrada no veículo. end end end end end) addEventHandler ("onPlayerQuit", root, function () -- Destroi o veículo criado pelo jogador quando ele desconecta do server. if (veh[source]) then destroyElement (veh[source]) veh[source] = nil end end)
  37. 1 point
    Illegal roleplay rules are now live so if you're interested in illegal roleplay it is strongly advised to read the thread on our forums.
  38. 1 point
    El error se entiende como: no se pudo llamar al resource sql. Ya que no esta el resource iniciado o contiene errores que impiden que inicie correctamente.
  39. 1 point
    The script just works if you put the car.dff (copcarla.dff) and car.txd (copcarla.txd) into the resource because "p" and "l" are inside of the car.txd file, like shown in Magic.TXD above. meta.xml <meta> <file src="indicatorshader.fx" type="client" /> <file src="car.dff" type="client" /> <file src="car.txd" type="client" /> <script src="client.Lua" type="client" /> </meta>
  40. 1 point
    Yes. If you typed /testcmd into the chat you would see that (you did). Looking at string representations of variables is a daily driver for debugging MTA:SA Lua scripts.
  41. 1 point
    Wow, I must have been pretty tired. True, that is the problem OP was talking about But I strongly discourage: slapztea should not use the same function for binding keys and event handling.
  42. 1 point
    I am not entirely sure, but it seems like you are trying to bind the keys to the server instead of the player. Maybe you are looking for another eventHandler. What about: addEventHandler ( "onPlayerJoin", getRootElement(), bindTheKeys )
  43. 1 point
    Você quer definir um dono para o carro?
  44. 1 point
    Nope, just the way you are doing it in your example. A flat structure, because each complexity in the structure will make it more complicated to save. You can later add a next layer on top of your table, to improve searching performance, if you so desire. Finding your item? Do it how a human would do, check every item in the list until you find the right one and stop searching.
  45. 1 point
    Eai pessoal tudo bom? Eu percebi que muitas das duvidas que o pessoal posta aqui no fórum e também na comunidade, são duvidas muito simples, principalmente com erros de logica, ou mau uso dos recursos da linguagem. Então decidi desenvolver um curso básico para auxiliar quem está começando, nesse curso básico vou abordar os seguintes assuntos: Lógica de Programação & Algoritmo; Condicionais & Variáveis (Básico); Sintaxe & Indentação; Boas Praticas de Programação; Como usar a Wiki; Funções(); Tabelas (Arrays); Scripts voltado ao MTA; Exercícios. Antes que venham falar "Quem é você para fazer um curso?", vou me apresentar: Eu me chamo Marcelo, trabalho com programação a cerca de 7 anos, já trabalhei com desenvolvimento, back-end e front-end. Atualmente eu trabalho na área de SI (Segurança da Informação) prestando serviço como pentester e consultor a uma empresa. Comecei a me envolver com Lua, por que joguei MTA por muito tempo, e percebi que a maioria dos servidores não atendia as minhas expectativas, então junto com um amigo, decidimos criar um novo servidor, o New Dream's Roleplay. Mas como o assunto aqui é o Tutorial, vou me ater apenas a ele, e deixo para falar do servidor outra hora. Lógica de Programação & Algoritmo Para deixar bem claro, vou usar as minhas definições das palavras durante o curso, porque acredito ser mais didática dessa forma. Antes de mais nada vamos deixar bem claro algumas coisas: Programação é lógica, a linguagem e etc, são apenas ferramentas para organizar e dar sentido a essa lógica. Portanto se você dominar a lógica de programação, poderá aplicar ela a qualquer linguagem. Tendo isso em mente, a aplicação da lógica podemos chamar de algoritmo. O Algoritmo por sua vez é uma sequencia de instruções, para a execução de uma tarefa. Claro que levando em consideração que o algoritmo conta com verificações, iterações e etc. Pois bem eu acredito que lógica só se aprenda fazendo, então vamos com alguns exemplos: Para facilitar a vida de alguns de vocês na compreensão, vou utilizar o Portugol como "linguagem" nesses exemplos, e recomendo que usem também nos exercícios. Para acessar o Portugol utilizem o link: http://lite.acad.univali.br/portugol/. Vamos começar pelo código mais repetido do mundo o "Olá Mundo" algoritmo OlaMundo; -- Aqui nos definimos o nome do Algoritmo inicio -- Aqui damos inicio ao mesmo imprima("Olá, Mundo!"); -- Aqui solicitamos que o Computador imprima a frase "Olá, Mundo!" fim -- Aqui encerramos Como podem reparar, toda a formação obedece uma lógica simples, você define, inicia, executa e encerra. Para termos um exemplo mais lúdico, vou usar linguagem padrão e descrever a seguinte situação: Acordar e sair para o trabalho. 01. Abrir os olhos; 02. Olhar o relógio; 03. Levantar da cama; 04. Ir ao banheiro; 05. Sair do quarto, e ir a cozinha; 06. Preparar o café da manha; 07. Sentar a mesa; 08. Comer o café da manha; 09. Lavar a louça do café da manha; 10. voltar ao quarto; 11. Vestir a roupa 12. Sair do Apartamento; 13. Descer o elevador; 14. Entrar no carro; 15. Ir ao trabalho. O exemplo acima é um algoritmo em linguagem padrão, quero que vocês percebam como ele utiliza uma sequencia lógica para executar uma tarefa. Agora, mais a frente iremos ver condicionais e verificações, mas já quero apresentar uma introdução sobre a mesma, nesse exemplo a cima, vamos adicionar uma verificação básica ali em cima na linha 02 01. Abrir os olhos; 02. Olhar o relógio CASO o relógio marque = 6:30 ENTÂO Faça a linha 03. CASO CONTRARIO espere até dar 06:30; 03. Levantar da cama; ... Nesse exemplo colocamos uma verificação simples, caso o horário seja o qual nos queremos, então vamos continuar com o algoritmo, isso é uma condição verdadeira ou falsa, e uma condição única, poderíamos adicionar outra condições por exemplo: 01. Abrir os olhos; 02. Olhar o relógio CASO o relógio marque = 6:30 && NÂO SEJA sabado OU domingo ENTÂO Faça a linha 03; 03. Levantar da cama; ... Aqui estamos adicionando outra verificação, e ambas precisam ser verdadeiras para que a sequencia se complete. Com esses exemplos em mente, vou deixar alguns exercícios para vocês, podem fazer tanto em linguagem padrão como em portugol (recomendo mais o portugol). 1. Acordar e ir ao trabalho; 2. Lavar o carro; 3. Um robô que pegue caixas; 4. Planejar uma viagem; 5. Jogar um jogo. Caso queiram, podem postar o código nesse tópico, e caso tenham alguma duvida, deixem logo a baixo. Só lembrando ao pessoal que já entende do assunto, ou pelo menos sabe o básico, vamos ajudar quem ta começando, todo mundo começou sem saber quase nada. Parte 02:
  46. 1 point
    РАСШИФРОВКА ПАРАМЕТРОВ (файл handling.cfg - раздел автотранспорт) В скобках указан диапазон числовых значений параметров, из которого выходить не рекомендуется vehicle identifier Номер модели и название модели в игре Mass Масса модели, в кг. ставить исходя из тех. характеристик Turn Mass Что-то вроде момента инерции. Параметр введен для улучшения реализма поведения. С его увеличением реакции модели становятся более вялыми и размазанными. в большинстве случаев примерно в 2-2.5 больше массы модели. Для легких и гоночных 1.4-1.8. Особо тяжелый транспорт – 3-6 массы. Drag (0.7…4.0) Комплексный коэффициент аэродинамического сопротивления - оказывает влияние на поведение модели на средних и больших скоростях. Создает эффект смазывания изображения на скорости. 0.7-1 для спортивных и гоночных 1-1.6 для обычных легковых 1.7-2.2 для джипов 2.2-3 траки, автобусы, спец.транспорт Centre Of Mass X (0) Расстояние от геометрического центра модели до центра тяжести по X всегда 0 Centre Of Mass Y (-0.4…0.4) Расстояние от геометрического центра модели до центра тяжести по Y, влияет на управляемость и «заносчивость» для улучшения управляемости ставить 0.1-0.25, в остальных случаях ставить правильно исходя из развесовки по осям. Centre Of Mass Z (-0.25…0) Расстояние от геометрического центра модели до центра тяжести по Z, влияет на опрокидываемость (устойчивость по вертикали) для всех -0.15…-0.2; -0.25 -для особенно валких. Percent Submerged Глубина погружения модели в воду, в процентах Traction Multiplier (0.55…1.0) Комплексный коэффициент сцепления с поверхностью. Аналогия – величина трения качения между поверхностью шины и дорожным покрытием. типичные значения 0.67-0.8. Нужно увязывать с настройкой подвески и ускорением. Зависит от особенностей модели. Traction Loss (0.55…1.05) Отвечает за потерю управляемости (срыв в занос). Аналогия - величина трения скольжения между поверхностью шины и дорожным покрытием. в большинстве случаев чуть меньше (на 1-3 пункта) параметра Traction multiplier Traction Bias (0.4…0.6) Регулирует баланс распределения двух предыдущих параметров между передней и задней осью. Т.е. меняет соотношение сцепных характеристик осей относительно друг друга. в большинстве случаев 0.5-0.52 в т.ч. для полного привода. Для тяжелого и грузового транспорта 0.48-0.5. Зависит от особенностей модели. NumberOfGears Количество скоростей в Коробке передача используется для увязки визуальных эффектов и звука двигателя при переключении передач не более 4 скоростей, параметр скорее бутафорский, лучше оставлять как у донора MaxVelocity Максимальная скорость ставить исходя из тех. характеристик, будет точно такой только при использовании флага use_maxsp_limit EngineAcceleration (12…33) Комплексный параметр объединяющий ускорение и мощность ~30 (600-1000 лс) для спортивных и гоночных; 25-29 (300-500 лс) для очень мощных современных; 21-24 (150-270 лс) для большинства обычных седанов и джипов; 16-21 (90-150 лс) для малолитражек и старья; до 16 все что осталось – развозной, автобусы, спецтранспорт EngineInertia (4.3…30) Отзывчивость или отдача мотора при нажатии на газ. Введен для увязки динамических характеристик с массой модели. 4.5-5.3 для спортивных и гоночных и машин, с очень высокой мощностью на единицу веса (более 300лс на тонну); 5.0-6.5 для мощных современных моделей (200-300лс на тонну); 6.5-8.5 для мощных, но тяжелых машин, в т.ч. джипов (150-200 лс на тонну); 8.5 -12 рядовые седаны и малолитражки; 13-23 -остальное DriveType Тип привода ставить исходя из тех. характеристик EngineType Тип двигателя (бензин, дизель, электро) ставить исходя из тех. характеристик BrakeDeceleration (6…50) Замедление при торможении. Аналогия – эффективность работы тормозов или длина тормозного пути. При использовании ABS сила торможения не регулируется! Без ABS – 7-13 для очень тяжелых машин и старья, 14-19 для классики и джипов, 19-35 для остальных. BrakeBias (0.45…0.6) Баланс распределения предыдущего параметра между осями. Аналогия – регулятор тормозных усилий. Ставить 0.53-0.59, меньше 0.51 будет разворачивать при торможении ABS Наличие/отсутствие АБС Ставить исходя из тех. характеристик SteeringLock (25…36) Угол поворота колес (он же выворот передних колёс) от продольной оси модели типовые значения 32-36 (в большинстве 34-35), в зависимости от управляемости Suspension Force Level (0.9…1.3) Комплексная жесткость подвески на сжатие 0.9-0.93 для джипов и тяжелой классики; 0.925-0.95 для грузовиков и др. тяжелой техники, комфортабельных и простых семейных машин; 0.935-0.97 для современных, малолитражек и полуспортивных купе; 0.96-1.05 для спортивных и современных купе; 1.05-1.2 для гоночных, заряженных и остальных осободубовых. Зависит от особенностей модели Suspension Damping Level (0.65…1.8) Комплексная жесткость подвески на отбой 0.65-0.73 – для старья и хлама, 0.73–0.8 –для рессорной классики, джипов семейных колымаг, пикапов, грузовиков; 0.81-0.88 для относительно современных и мощных машин, с независимой подвеской, малолитражек; 0.89-0.93 для современных мощных, спортивных и купе; 0.93 -1.1 для гоночных и спорткаров -машина прилипает к земле. Зависит от особенностей модели. Suspension HighSpdComDamp (0…20) Коэффициент корректирующий два предыдущих параметра с ростом скорости. Аналогия - на большой скорости машину начинает бросать и мотать. 5-15 для тяжелого, неуклюжего,плохо переносящего средние и большие скорости транспорта (автобусы, рыдваны, тракторы, спецтранспорт и т.п.) -. Для всех остальных 0. Suspension upper limit (0.1…0.4) Крайняя верхняя точка хода подвески 0.31-0.35 – серьезные внедорожники и очень тяжелый транспорт; 0.28-0.31 паркетники, классика, пикапы, грузовики; 0.25-0.28 основная масса легковых машин; 0.22-0.25 спортивные, мощные, современные купе; 0.20-0.23 жесткие, гоночные и очень мощные в т.ч. заряженные; 0.17-0.20 экстремальный и уникальный транспорт Suspension lower limit (-0.05…-0.25) Крайняя нижняя точка хода подвески. Зависит от изначально установленной посадки в редакторе. Выставлять исходя из нормального для модели дорожного просвета. Меньше -0.1 ставить не рекомендуется т.к. подвеска перестает работать и модель подскакивает на каждой кочке Suspension bias between front and rear (0.4…0.6) Комплексный параметр, распределяющий баланс настройки подвески (жесткость на сжатие и отбой) между осями. Косвенно влияет на наклон кузова в горизонтальной плоскости. Без необходимости не трогать (0.5 –норма). Для рессорных пикапов, хотродов и драгстеров 0.44-0.48. Для грузовиков и вэнов 0.47-0.49. Suspension anti-dive multiplier (0…0.5) Регулирует эффект раскачки кузова при старте, торможении и резких поворотах. Что-то типа визуальной мягкости подвески. Для тяжелых, с мягкой и длинноходной подвеской 0.0-0.15; для обычных и грузовых 0.15-0.25. Для спортивных и легких 0.25-0.3. Для гоночных и особо дубовых 0.3-0.4 SeatOffsetDistance Расстояние от двери до сидения CollisionDamageMultiplier (0.2…0.6) Коэффициент повреждаемости, пороговое значение силы удара при котором проявляется повреждение. Своего рода чувствительность коллизии. Для тяжелых траков и т.п. 0.35-0.4; для джипов и крепких машин 0.4-0.45; для обычных 0.44-0.49; для легких и маленьких 0.49-0.54. MonetaryValue Цена модели в у.е. Используется при покупке в автосалонах и расчете статистики ущерба. ModelFlags IS_VAN Отвечает за анимацию задних двустворчатых дверей у вэнов IS_BUS Отвечает за автобусное поведение и анимацию (останавливается на остановках, принимает пассажиров) IS_LOW Более низкая (спортивная) посадка за рулем IS_BIG Отвечает за проезд поворотов и углов улиц с учетом больших габаритов модели и включение звукового сигнала при езде задним ходом REVERSE_BONNET Капот будет открываться наоборот – петли впереди HANGING_BOOT Багажник открывается вверх (задняя дверь у джипов, универсалов) TAILGATE_BOOT Багажник открывается вниз (дверка кузова у пикапов) NOSWING_BOOT Запрет анимации багажника NO_DOORS Запрет анимации дверей TANDEM_SEATS Специальная анимация посадки для спец. транспорта типа mower, sweeper, kart, tractor, tug, dune и др. SIT_IN_BOAT Анимация посадки в лодку (кроме тех случаев, когда в лодке надо стоять) CONVERTIBLE Точно не известно. Есть подозрение что это спец. анимация выкидывания педов из кабриолетов. NO_EXHAUST Запрет анимации выхлопа (электропривод) DBL_EXHAUST Анимация для выхлопа из двух труб по бокам NO1FPS_LOOK_BEHIND Запрет на обратный вид (когда камера перед машиной и направлена назад) FORCE_DOOR_CHECK Не известно AXLE_F_NOTILT Запрет на наклон передних колес при работе подвески (не как у Татры) Устанавливать для всех моделей AXLE_F_SOLID Передние колеса выравниваются параллельно всем остальным AXLE_F_MCPHERSON Анимация передних колес имитирует работу подвески типа «макферсон» AXLE_F_REVERSE Делает обратную анимацию для флага AXLE_F_MCPHERSON -используется вместе с ним AXLE_R_NOTILT Запрет на наклон задних колес при работе подвески (не как у Татры) Устанавливать для всех моделей AXLE_R_SOLID Задние колеса выравниваются параллельно всем остальным AXLE_R_MCPHERSON Анимация задних колес имитирует работу подвески типа «макферсон» AXLE_R_REVERSE Делает обратную анимацию для флага AXLE_R_MCPHERSON -используется вместе с ним FORCE GROUND CLEARENCE Усиливает прижимную силу на скорости. Аналогия – аэродинамическая прижимная сила от антикрыльев и обвеса. HandlingFlags 1G_BOOST Дополнительная прибавка крутящего момента при старте. Задумано для более легкого преодоления холмов и крутых подъемов. 2G_BOOST Дополнительная прибавка крутящего момента на средних и высоких скоростях. Задумано для имитации работы турбины/чарджера (подхват после турбоямы). NPC_ANTI_ROLL Не известно NPC_NEUTRAL_HANDL Модель не использует настройки к-рые ей заданы когда за рулем NPC (т.е. робот). Этот флаг включается автоматически если настройки некорректны. Например садишься в машину а она не трогается с места, или ведет себя неправильно, есть какой-то баг. а вот если NPC за рулем той же машины - она ведет себя нормально. NO_HANDBRAKE Отключение ручного тормоза STEER_REARWHEELS Поворачивают задние колеса, как у автопогрузчика HB_REARWHEEL_STEER Задние колеса тоже поворачивают (подруливают), как у монстртрака ALT_STEER_OPT Не известно WHEEL_F_NARROW2 Передние колеса в 2 раза (на глаз) уже WHEEL_F_NARROW Передние колеса в 1.5 раза (на глаз) уже WHEEL_F_WIDE Передние колеса в 1.5 раза шире WHEEL_F_WIDE2 Передние колеса в 2 раза шире WHEEL_R_NARROW2 Задние колеса в 2 раза уже WHEEL_R_NARROW Задние колеса в 1.5 раза уже WHEEL_R_WIDE Задние колеса в 1.5 раза шире WHEEL_R_WIDE2 Задние колеса в 2 раза шире HYDRAULIC_GEOM Необходимый флаг для всех моделей-лоурайдеров HYDRAULIC_INST Изначально установленная гидравлика HYDRAULIC_NONE Запрет на установку гидравлики NOS_INST Установленный нитро ускоритель OFFROAD_ABILITY Улучшенное сцепление на грязной поверхности OFFROAD_ABILITY2 Улучшенное сцепление на песке HALOGEN_LIGHTS Свет фар более яркий, с голубым оттенком (эффект галогеновых фар) PROC_REARWHEEL_1ST Блокировка заднего межколесного дифференциала (для любого типа привода) USE_MAXSP_LIMIT Жесткое фиксирование максимальной скорости. Если флаг не ставить максималка достигается исходя из величины параметра EngineAcceleration LOW_RIDER Необходимый флаг для всех моделей-лоурайдеров STREET_RACER Параметр позволяет "тюнинговать" или как минимум загонять машину в "Wheel Arch Angels", при этом необходимо поменять последнюю цифру в vehicles.ide на 2, чтобы "Архангелах" ставились все диски. SWINGING_CHASSIS Отвечает за раскачку кузова в горизонтальной плоскости (из стороны в сторону) front lights Тип (размер) передних фар rear lights Тип (размер) задних фар vehicle anim group Модель анимации посадки/высадки исходя из типа транспортного средства Для настройки авто используйте Ingame Handling Editor (hedit) или же используйте такую функцию как setVehicleHandling
  47. 1 point
    Introduction Vehicle indicators are mostly seen on other GTA modifications where the mod 'IVF - Improve Vehicle Features' is compatible. This mod allows for light modifications such as police flashlights, custom LED flashers, indicators and much more. These features are sought after by MTA roleplaying servers a lot. This guide aims to introduce 3D modelers to prepare models for customisable lights, which then requires coded shaders to work. Anything related to scripting is not included in this guide. The guide assumes that the modeler has basic understanding of importing and exporting models. Editing existing Huntley for indicator lights With Huntley imported into 3ds Max, isolate the mesh called 'chassis' as it is the only component that needs working lights. As seen the car has 4 lights; right tail light, left tail light, right headlight and left headlight. All 4 has their own material assigned for them to act each their own way. The material color codes are hardcoded in the game telling it when to show illuminated brake lights for when the car brakes and so on. For this custom vehicle however, any geometry meant for custom vehicle lighting needs white color code and a custom texture name for shadering to work. Before anything, it's required to get the custom lighting texture ready. For this guide, vehiclelights128 and its illuminated version works perfectly fine. These needs be renamed to customRRLightsOff and customRRLightsOn and so forth. The 'RR' is for 'right rear', where as 'LR' would be 'left rear'. This needs be done for front too, so in total 4 'off' images are needed while only one 'on' is needed, as it can simply be instanced when shadering. Below is a step-step process on editing Huntley's geometry and adding custom indicators. Add an 'Editable Poly' modifier to the model. Press '5' key on keyboard which enables 'Select by Element'. Select the two rear light meshes, ensure they are both highlighted. On 'Modify Panel' scroll down and find 'Slice Plane', click that. This creates a rectangle that has a line-preview for the cut. Align the plane to the lights and create two cuts for the indicator lights. Select one side of the geometry that was cut by using 'Select by Polygon'. On the modifier stack, click 'Collapse all', leaving only 'Editable mesh' on the stack. Press 'M' key for 'Material browser'. Create a new GTA material. In the texture slot, add in the 'customRRLightsOff'. On material browser, click 'Assign material to Selection'. Note that this needs be done for the left side too but with different material and texture. Apply a new modifier on the model called 'Unwrap UVW'. Press 'Open UV editor'. On the UV editor, enable 'Select by polygon'. Grab the UV island and drag it onto the orange section of the image, which is for indicator lights. On modifier stack, collapse all, to save the new UV's. Above: example of what can be achieved. Front lights section already has indicator lights, so all that needs doing is 2 new materials with each their own light texture, like done on rear side. The 4 new textures needs be added to the car's .txd file. Model is now ready for export. Now all that's needed is MTA scripting for the light shaders to work. Exact same process can be applied for creating custom emergency lights. Note that it is not necessary to have these 128x128 textures in the model. They can be downscaled to 4x4 in the .txd and then a MTA shader script can apply the originals, which greatly reduces the size of download. This means it'll download 4 images which are then instanced onto every custom model using the lights. To put it short, each .txd will have 4 placeholder-images of 4x4 resolution rather than 4 images of 128x128 resolution.
  48. 1 point
    setPlayerWantedLevel takePlayerMoney onClientGUIClick - Supondo que seja clicando em um botão do painel GUI.
  49. 1 point
  50. 1 point
    You're the co-owner of a server (R9 Freeroam) that has been banned from MTA because of its leaders and admins constantly engaging in illegal activity (DDoS'ing their own players and other servers). After this ban, you guys decided to start evading it by switching hosts. This, together with your known involvement in plotting attacks (both in person to your fellow server admins/(co)owners, and on the R9/Morgue Freeroam discord), has resulted in us also banning the server leadership and high admins that we consider taking part in all these illegal acts and evading the actions taken, from MTA. As co-owner of this malicious server, you personally received a permaban, and not everyone involved did. Please refer to the extended explanation given to the owner (ScreaM) of R9 freeroam: The owner had been banned for DDoS a few years ago, and after evading it for a while he found his other PC was still banned from the old incident. He appealed, and got unbanned; it didn't take a week for him to DDoS yet another player. After this, our investigation turned up links between your server and a clan that focusses merely on DDoS activity rather than playing. It was no surprise that more people, similar to the DDoS'ing owner, were coming together to call R9 Freeroam their home. Furthermore, we confirmed the spirit that all of the banned server leadership had (and high admins.. not all admins/staff), which was a drive to discuss and execute DDoS attacks. In the investigation that followed, you weren't compliant and mostly resorted to personal attacks on me, but you gotta realize I got a thick skin and will go far if we need to protect others on MTA against a certain group of individuals. Besides the original investigation, I have also witnessed all co-owners and admins that are currently banned, discuss new attacks to launch. You quickly wiped the channel and banned me from your discord when you found out. All bans given are a result of either identification from openly discussing attacks/malicious actions while on the MTA server itself, or solid links between the Discord server tied to R9/Morgue Freeroam in which said individuals were listed as server admins/owners and discussing attacks, furthermore confirmed in identity and serial by linked activity on the MTA server. Please don't forget that a reality in which a player needs to use a VPN in order to safely join a certain server (and will be at risk when they piss someone off through gameplay), is one that we will not accept. You guys even went as far as to create "databases" full of aggregated player serial/IP for easy lookup to DDoS them if they frustrated you while on another server. *Note: this will be a template reply for anyone that will try to appeal a ban like this, we are unfortunately not open for arguing, as I have spent a few hours doing that fruitlessly during my investigation. Our decisions are final.