Jump to content

Search the Community

Showing results for tags 'object'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Multi Theft Auto: San Andreas 1.x
    • Support for MTA:SA 1.x
    • User Guides
    • Open Source Contributors
    • Suggestions
    • Ban appeals
  • General MTA
    • News
    • Media
    • Site/Forum/Discord/Mantis/Wiki related
    • MTA Chat
    • Other languages
  • MTA Community
    • Scripting
    • Maps
    • Resources
    • Other Creations & GTA modding
    • Competitive gameplay
    • Servers
  • Other
    • General
    • Multi Theft Auto 0.5r2
    • Third party GTA mods
  • Archive
    • Archived Items
    • Trash

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Member Title


Gang


Location


Occupation


Interests

  1. Hi, Im trying to import some objects from GTA IV to my MTA Server. I watched some videos and in result I made dff, col and txd file. When I uploaded it to my server the object model was exactly like I want it to be. The collision was working fine too, but the object texture was blank - it looks like the same with the txd file teplaced and without the txd file replaced, so I think that the problem is with this file. I was trying to find a solution but it didnt give an effect. For better clarity I'm explaining how I add an material to the object. https://imgur.com/a/laikQkp - Please read the descriptions of the images, start reading from the bottom of the page. Please help me and dont know what am I doing wrong.
  2. Con el CommandHandler "Sube" funciona, pero con el Pe, ¿Que hace? Crea el objeto, pero no lo redirecciona con el SetElementPosition y attach, es como si lo ignorara... ¿Alguna solución? function SubenPasajeros () if CantidadDeAsientos >= 0 then if Asiento1 == 0 then Asiento1 = 1 local vehicle = getPedOccupiedVehicle( client ) x1, y1, z1 = getElementPosition ( client ) Asiento1 = createObject (2035, 1421.958984375, 2624.4677734375, 11.392612457275) setElementPosition ( Asiento1, x1, y1, z1) attachElements( Asiento1, vehicle, 0.95, 0.6, 0, 0, 0, 0 ) --Fila 1 A outputChatBox ("Asiento1") else if Asiento2 == 0 then Asiento2 = 1 outputChatBox ("Asiento2") local vehicle = getPedOccupiedVehicle( client ) x1, y1, z1 = getElementPosition ( client ) Asiento2 = createObject (2035, 1421.958984375, 2624.4677734375, 11.392612457275) setElementPosition ( Asiento2, x1, y1, z1) attachElements( Asiento2, vehicle, 0.5, -0.2, 0, 0, 0, 0 ) --Fila 2 B end end end addCommandHandler("sube",SubenPasajeros) function PrenderFuncSubenPasajeros () outputChatBox ("JEJE") setTimer ( SubenPasajeros, 500, 1) end addCommandHandler("pe",PrenderFuncSubenPasajeros)
  3. What I wanted to do, was that the user to buy a certain accessory color and object, that is saved and at the beginning, not only can see it, but also can see others. Server: function Cortina1(paintjobID, color) local vehicle = getPedOccupiedVehicle( client ) local player = client if ( vehicle ) then local pos = {getElementPosition( vehicle )} Cortinapuesta = createObject( 1000, pos[1], pos[2], pos[3] ) attachElements( Cortinapuesta, vehicle, 0, 0, 0, 0, 0, 0 ) triggerClientEvent (root, "setShader", resourceRoot, paintjobID, color) end end addEvent("PonerCortina", true) addEventHandler("PonerCortina", resourceRoot, Cortina1) function CancelarCortina() local vehicle = getPedOccupiedVehicle( source ) if ( vehicle ) then destroyElement(Cortinapuesta) end end addEvent("SacarCortina", true) addEventHandler("SacarCortina", root, CancelarCortina) ----------------------------------------------------------------------------------------------------- function addPJfction (player) triggerClientEvent (getRootElement(),"addPJ2", getRootElement(), player ) end addEvent( "addPJ", true ) addEventHandler( "addPJ", resourceRoot, addPJfction ) function removePJfction (player) triggerClientEvent (getRootElement(),"removePJ2", getRootElement(),player ) end addEvent( "removePJ", true ) addEventHandler( "removePJ", resourceRoot, removePJfction ) Client: Ventana1 = createMarker (2194.4677734375, 1440.5966796875, 10.8203125-1, "cylinder", 1.5, 0, 255, 0, 170 ) local NormalTextColour = "FFFB0202" function mapLoad ( Bondi2018OBJETOS ) local txdCortinas1518 = engineLoadTXD( "objetos/metalpar1518/vehicle.txd" ) local dffCortinas1518 = engineLoadDFF( "objetos/metalpar1518/spl_b_mar_m.dff", 0 ) engineImportTXD( txdCortinas1518, 1000 ) engineReplaceModel( dffCortinas1518, 1000 ) end addEventHandler ( "onClientResourceStart", resourceRoot, mapLoad ) addEventHandler("onClientMarkerHit", Ventana1, function(localPlayer) if localPlayer == getLocalPlayer() then Ventana = guiCreateWindow(997, 226, 228, 743, "BONDI 2018 - Taller \"Libertad\"", false);guiSetVisible(Ventana, true) guiWindowSetSizable(Ventana, false) guiSetProperty(Ventana, "CaptionColour", "FF0EF1E3") showCursor(true) veh = getPedOccupiedVehicle( localPlayer ) Boton1 = guiCreateButton(15, 66, 108, 31, " CORTINAS", false, Ventana); guiSetProperty(Boton1, "NormalTextColour", "FFFB0202") Boton2 = guiCreateButton(15, 107, 108, 31, " Parachoques", false, Ventana);guiSetProperty(Boton2, "NormalTextColour", "FFFB0202") Boton3 = guiCreateButton(15, 148, 108, 31, " ASIENTOS", false, Ventana);guiSetProperty(Boton3, "NormalTextColour", " FFFB0202") Boton4 = guiCreateButton(15, 189, 108, 31, " VIDRIOS", false, Ventana);guiSetProperty(Boton4, "NormalTextColour", "FFFB0202") Boton5 = guiCreateButton(15, 230, 108, 31, " OPTICAS", false, Ventana);guiSetProperty(Boton5, "NormalTextColour", "FFFB0202") Boton6 = guiCreateButton(15, 271, 108, 31, "", false, Ventana);guiSetProperty(Boton6, "NormalTextColour", " FFFB0202") Boton7 = guiCreateButton(15, 312, 108, 31, "", false, Ventana);guiSetProperty(Boton7, "NormalTextColour", " FFFB0202") Boton8 = guiCreateButton(15, 353, 108, 31, "", false, Ventana);guiSetProperty(Boton8, "NormalTextColour", " FFFB0202") Boton9 = guiCreateButton(15, 394, 108, 31, "", false, Ventana);guiSetProperty(Boton9, "NormalTextColour", " FFFB0202") BotonCERRAR = guiCreateButton(15, 700, 108, 31, "CERRAR", false, Ventana);guiSetProperty(BotonCERRAR, "NormalTextColour", "FFFB0202") end end ) Ventana2 = guiCreateWindow(997, 226, 228, 743, "BONDI 2018 - Taller \"Libertad\"", false);guiSetVisible(Ventana2, false);guiWindowSetSizable(Ventana2, false);guiSetProperty(Ventana2, "CaptionColour", "FF0EF1E3") Boton1 = guiCreateButton(60, 66, 108, 31, "Cortinas Simples", false, Ventana2); guiSetProperty(Boton1, "NormalTextColour", "FFFB0202") Boton2 = guiCreateButton(15, 107, 108, 31, " Turquesas", false, Ventana2);guiSetProperty(Boton2, "NormalTextColour", "FFFB0202") Boton2b = guiCreateMemo(150, 107, 64, 31, "2500", false, Ventana2); guiSetProperty(Boton2b, "NormalTextColour", "FFFB0202");guiMemoSetReadOnly( Boton2b, true ) Boton3 = guiCreateButton(15, 148, 108, 31, " 2", false, Ventana2);guiSetProperty(Boton3, "NormalTextColour", " FFFB0202"); Boton4 = guiCreateButton(15, 189, 108, 31, " 3", false, Ventana2);guiSetProperty(Boton4, "NormalTextColour", "FFFB0202") Boton5 = guiCreateButton(15, 230, 108, 31, " 4", false, Ventana2);guiSetProperty(Boton5, "NormalTextColour", "FFFB0202") Boton6 = guiCreateButton(15, 271, 108, 31, "5", false, Ventana2);guiSetProperty(Boton6, "NormalTextColour", " FFFB0202") Boton7 = guiCreateButton(15, 312, 108, 31, "6", false, Ventana2);guiSetProperty(Boton7, "NormalTextColour", " FFFB0202") Boton8 = guiCreateButton(60, 353, 108, 31, "Cortinas Completas", false, Ventana2);guiSetProperty(Boton8, "NormalTextColour", " FFFB0202") Boton9a = guiCreateButton(15, 394, 108, 31, "Turquesas", false, Ventana2);guiSetProperty(Boton9a, "NormalTextColour", " FFFB0202") Boton10a = guiCreateButton(15, 435, 108, 31, "Rojas", false, Ventana2);guiSetProperty(Boton10a, "NormalTextColour", " FFFB0202") Boton11a = guiCreateButton(15, 476, 108, 31, "Azules", false, Ventana2);guiSetProperty(Boton11a, "NormalTextColour", " FFFB0202") Boton12a = guiCreateButton(15, 517, 108, 31, "Blancas", false, Ventana2);guiSetProperty(Boton12a, "NormalTextColour", " FFFB0202") Boton13a = guiCreateButton(15, 558, 108, 31, "Celestes", false, Ventana2);guiSetProperty(Boton13a, "NormalTextColour", " FFFB0202") BotonTOTAL = guiCreateMemo (15, 650, 60, 31, "Total:", false, Ventana2);guiSetProperty(BotonTOTAL, "NormalTextColour", "FFFB0202");guiMemoSetReadOnly( BotonTOTAL, true ) BotonTOTAL2 = guiCreateMemo (75, 650, 60, 31, "0", false, Ventana2);guiSetProperty(BotonTOTAL2, "NormalTextColour", "FFFB0202");guiMemoSetReadOnly( BotonTOTAL2, true ) BotonCOMPRAR = guiCreateButton (135, 650, 65, 31, "COMPRAR", false, Ventana2);guiSetProperty(BotonCOMPRAR, "NormalTextColour", "FFFB0202") BotonCERRAR2 = guiCreateButton(15, 700, 108, 31, "CERRAR", false, Ventana2);guiSetProperty(BotonCERRAR2, "NormalTextColour", "FFFB0202") addEventHandler("onClientGUIClick", guiRoot, --VENTANA function() local getGui = guiGetVisible(Ventana) if source == BotonCERRAR then if getGui then guiSetVisible(Ventana, false) showCursor(false) veh = getPedOccupiedVehicle( localPlayer ) end end end ) -------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- addEventHandler("onClientGUIClick", guiRoot, --VENTANA function() local getGui = guiGetVisible(Ventana2) if source == BotonCERRAR2 then if getGui then guiSetVisible(Ventana2, false) showCursor(false) veh = getPedOccupiedVehicle( localPlayer ) triggerServerEvent("SacarCortina", localPlayer, localPlayer) end end end ) addEventHandler("onClientGUIClick", guiRoot, --VENTANA2 = CORTINAS function() local getGui = guiGetVisible(Ventana) if source == Boton1 then if getGui then guiSetVisible(Ventana, false) guiSetVisible(Ventana2, true) veh = getPedOccupiedVehicle( localPlayer ) end end end ) --------------------------------------------------------------------------------------------------------- addEventHandler("onClientGUIClick", guiRoot, --VENTANA2 = CORTINAS > Completas > Turquesas function () local getGui = guiGetVisible(Ventana2) if source == Boton9a then local color = "nada" triggerServerEvent("PonerCortina", resourceRoot, paintjobID, color) PrecioCortinasCompletas = 3500 PrecioTotal = PrecioCortinasCompletas guiSetText(BotonTOTAL2, PrecioCortinasCompletas) else if source == Boton10a then --ROJAS local color = "red" triggerServerEvent("PonerCortina", resourceRoot, paintjobID, color) PrecioCortinasCompletas = 3500 PrecioTotal = PrecioCortinasCompletas guiSetText(BotonTOTAL2, PrecioCortinasCompletas) end end end ) addEvent( "addPJ2", true ) addEventHandler( "addPJ2", getLocalPlayer(), CortinasCompletas ) function addPaintjob2(paintjobID, color) outputChatBox("the color is:" .. color) if color == "red" then CortinasRojas = dxCreateTexture ( "CortinasRojas.png" ) engineRemoveShaderFromWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) shader_cars , tec = dxCreateShader ( "shader.fx" ) engineApplyShaderToWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) dxSetShaderValue (shader_cars,"TX0",CortinasRojas) elseif color == "blue" then CortinasAzules = dxCreateTexture ( "CortinasAzules.png" ) engineRemoveShaderFromWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) shader_cars , tec = dxCreateShader ( "shader.fx" ) engineApplyShaderToWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) dxSetShaderValue (shader_cars,"TX0",CortinasAzules) elseif color == "Nada" then outputChatBox ("Asi como está") end end addEvent( "setShader", true ) addEventHandler( "setShader", resourceRoot, addPaintjob2 ) -------------------------------------------------------------------------------------- addEventHandler("onClientGUIClick", guiRoot, --VENTANAS > BOTON COMPRAR function(localPlayer) local getGui = guiGetVisible(Ventana2) local money = getPlayerMoney (localPlayer) if source == BotonCOMPRAR then if (money > PrecioTotal) then outputChatBox ("Dinero CALCULADO") takePlayerMoney ( PrecioTotal ) outputChatBox ("Usted ha comprado las cortinas") guiSetVisible(Ventana2, false) showCursor (false) else outputChatBox ("No tiene el dinero suficiente para comprarlas!!") end end end)
  4. Hello. Sry for my english. I creating object: local element_object = createObject(13025, 123.123, 123.123, 123.123, 123.123, 123.123, 123.123) I creating collision: local element_col = createColCircle(0.0, 0.0, 25.0) I attach collision to object attachElements(element_col, element_object) And when i hit collision onElementColShapeHit not call. wtf? what i doing wrong? But i attach object to collision then everything works. attachElements(element_object, element_col) -- change variables
  5. best program to create new object? How to? I used 3ds max.. is there something better?
  6. Hi all, I'm in search for a component/library having positioning controls like on the pic shown. Here's a samp's "Attached object editor" screenshot, but I've seen the same solutions being 100% lua-implemented on several MTA (many of them were not that "professionally built") servers, this "editor mode" looked the same everywhere, so I guess there could be an open-source issue.
  7. How do I delete an object inside an interior? I select the "World Object Remove" and click on the object but do not delete, thank you already
  8. How can i make marker that can only be hit by object (not player on foot, and not vehicle!)
  9. Hi everyone, So recently I have been working on some scripting with the famous bone_attach script and I've noticed something important, when I attach object to the client and the client teleports to another interior/dimension, the objects gets invisible but when I go back to the 0 dimension&interior, It gets visible ! plus, even If I created and attached the object in dimension/interior other than 0, its Invisible, I teleport to 0 it gets visible . In this case, how should I make the object that attached to the client visible when he goes to another dimension & interior ? Any help is appreciated .
  10. i want make a script, which create objects every 15 minutes, and when i click on a object, then play a animation, and remove object & give me money, how to make this? sorry for my bad english.. :c
  11. Hello, I've been struggling with this last part of a script I'm making. Basically an object spawns, and needs to be launched forwards. However, this doesn't happen. the object just sits still. function rustlerCreateProjectile() local vehicle = getPedOccupiedVehicle(localPlayer) if(vehicle)then if getElementModel(vehicle) == 476 and rustler50calstate == 1 then outputChatBox ("50cal firing") elseif rustler20mmstate == 1 then outputChatBox ("20mm cannons firing") elseif rustler37mmstate == 1 then local x, y, z = getElementPosition(vehicle) local rx, ry, rz = getElementRotation(vehicle) local projectile37mm = createObject (2686, x, y, z, rx, ry, rz, true) local projectileattach = attachElements (projectile37mm, vehicle, 0, 4.3, -0.15) setTimer (function() detachElements (projectile37mm) end, 50, 1) setTimer ( function() setElementVelocity(projectile37mm, 0, 0, 50) --this is the part that I cannot get to work --destroyElement ( projectile37mm ) end, 50, 1 ) outputChatBox ("37mm cannon firing") end end end bindKey("mouse1", "down", rustlerCreateProjectile) What am I missing?
  12. Hello, I would like to ask for the help to create a system to rotate an object when I hold a certain button , It will only stop after I release objectRotation = 0; objeto = createObject ( 1852,2714,-1756.2700195313,77.559997558594, 0, 0, 0 ) function func () objectRotation = objectRotation + 1.20 setElementRotation(objeto, 0, 0, objectRotation) end function func2 () objectRotation = objectRotation - 1.20 setElementRotation(objeto, 0, 0, objectRotation) end bindKey ( "2", "down", func2 ) bindKey ( "3", "down", func )
  13. Hi everyone! Can someone help me that, if I click on specified object, then run a function named "startit1"
  14. Hi guys, I'm trying to learn how to do a resource to hold a ball when the player collides, and then click to shoot it in the current camera direction. Im a little lost , I searched and tried with moveObejct but the result was too badly... Here some portions of code: ball = createObject(1598, 1347.8164, 2127.0234, 10.3, 300, 360, 300, false) attachElements ( ball, player, 0, 0.5, -0.75 ) local rotz = tonumber(getPedRotation(player)) local xt,yt,zt = getElementPosition(player) detachElements(ball, player) xt = xt + (math.cos(math.rad(rotz+90)) * 1.2) yt = yt + (math.sin(math.rad(rotz+90)) * 1.2) moveObject(ball, 2500, xt, yt, zt, math.random(10, 90), math.random(10, 90), math.random(10, 90)) If you can help me with something or give me a hint, I will be grateful!
  15. if AdminGate then destroyElement(AdminGate) end local AdminGate = createObject ( 1560, 1346.78, -1759.83630, 12.5, 0, 0, 0 ) local state = 0 function move() if state == 0 then moveObject ( AdminGate, 2500, 1348.68652, -1759.83630, 12.5) state = state + 1 elseif state == 1 then moveObject ( AdminGate, 2500, 1346.78, -1759.83630, 12.5) state = state - 1 end end addCommandHandler("coopajto", move ) fileDelete("c.lua") when i type the command, the door move just for me how to fix this?
  16. i want create a cool building map, but i dont know which objects are good for this i do not want use jetdoor object, because this not so nice can anyone recommend object for this? sorry for my very bad English:c
  17. function dependent(player) local accountName = getAccountName ( getPlayerAccount ( player ) ) local hour = getAccountData ( playeraccount, "Játszott idő-hours") if hour = 30 then aclGroupAddObject (aclGetGroup("Dependent"), "user."..accountName) end end i got this error: [22:44:11] ERROR: Loading script failed: jatszottido\ji.lua:86: 'then' expected near '=' how to fix this?
  18. Hi everyone! have here server-side script local col = createColCircle(170, -377, 15) local object = createObject(737, 175, -377, 6) print(isElementWithinColShape(object, col)) -- print false Can anyone tell me, why i got false, when object IN colshape? Object and colshape have same coordinates.
  19. http://imgur.com/SbpALvs /sorry for my bad english, and paint draw/ this is a "road object" from car school in singleplayer. not find it anywhere the id
  20. Everythink is working in the code, only the rotating not. When i press mouse1 then the weapons and the object will be created but its not rotating. This rotating function makes possible to rotate the object called "object3" to that direction where the "misc_a" (vehicle component) and the "misc_c" (vehicle component) is rotating at. The problem is that its not rotating the object. I hope you can help me again. Thanks in advance! client object3 = {}; mg1 = {}; mg2 = {}; addEvent ( 'fire_mg',true ); addEventHandler ( 'fire_mg',root, function ( aVehicle,aX,aY,aZ ) if aVehicle and aX and aY and aZ then object3 [ aVehicle ] = createObject ( 357, aX,aY,aZ) attachElements ( object3 [ aVehicle ], aVehicle, -0.05,10,3, 0,0,90 ) mg1 [ aVehicle ] = createWeapon("m4", aX,aY,aZ) mg2 [ aVehicle ] = createWeapon("m4", aX,aY,aZ) setWeaponFiringRate(mg1 [ aVehicle ], 20) setWeaponFiringRate(mg2 [ aVehicle ], 20) setWeaponState(mg1 [ aVehicle ], "firing") setWeaponState(mg2 [ aVehicle ], "firing") attachElements(mg1 [ aVehicle ], object3 [ aVehicle ], 0.2, 0.2, 0, 0, 0, 0) attachElements(mg2 [ aVehicle ], object3 [ aVehicle ], 0.2, -0.3, 0, 0, 0, 0) setElementData ( aVehicle,'mgFireOn',true ); local veh = getPedOccupiedVehicle(localPlayer) setElementData ( aVehicle,'object3',object3 [ aVehicle ] ); addEventHandler("onClientRender",root,rotate_object) end end ); function rotate_object() local veh = getPedOccupiedVehicle(localPlayer) local _,_,rz = getVehicleComponentRotation(veh, "misc_a") local rx,_,_ = getVehicleComponentRotation(veh, "misc_c") triggerServerEvent("rotateWeapon", localPlayer, rx,rz) end server function rotateWeapon(rx,rz) outputChatBox("rotate_s") local object3 = getElementData ( aVehicle, "object3" ) rx = (-rx) setElementAttachedOffsets ( object3, 0, 5.25, 2.45, 0, rx+7, rz+96) end addEvent("rotateWeapon", true) addEventHandler("rotateWeapon", root, rotateWeapon) function fire ( aPlayer ) if aPlayer and getElementType ( aPlayer ) == 'player' then if isPedInVehicle ( aPlayer ) then local aVehicle = getPedOccupiedVehicle( aPlayer ); if aVehicle and getElementModel ( aVehicle ) == 592 then local aX,aY,aZ = getElementPosition ( aVehicle ); triggerClientEvent ( root,'fire_mg',root,aVehicle,aX,aY,aZ ); end end end end function bind_start() for _,aPlayers in ipairs ( getElementsByType ( 'player' ) ) do bindKey ( aPlayers,'mouse1','down',fire ); end end addEventHandler ( 'onResourceStart',resourceRoot,bind_start) function bind_join() bindKey ( aPlayers,'mouse1','down',fire ); end addEventHandler ( 'onPlayerJoin',root,bind_join )
  21. Why does the setElementAttachedOffsets (in server side) not work? i got no debugscript client function onEnter2(player,seat) local model = getElementModel(source) if player == localPlayer and (model == 602) and seat == 0 then local veh = getPedOccupiedVehicle(localPlayer) local x,y,z = getElementPosition(veh) local object = createObject ( 357, x,y,z) attachElements(object, veh, 0,0,1,0,0,0) createWeapon_c(veh,object) setElementData(localPlayer,"object", object) addEventHandler('onClientRender', root, rotate_object ) end end addEventHandler("onClientVehicleEnter", root, onEnter2) function rotate_object() local veh = getPedOccupiedVehicle(localPlayer) local object = getElementData(localPlayer,"object") local _,_,rz = getVehicleComponentRotation(veh, "misc_a") local rx,_,_ = getVehicleComponentRotation(veh, "misc_b") triggerServerEvent("rotateWeapon", root, object,rx,rz) end and the server (which is actualy not woroking) function rotateWeapon(object,rx,rz) outputChatBox("rotate_s") rx = (-rx) setElementAttachedOffsets ( object, 0, 0, 1, 0, rx+7, rz+96) end addEvent("rotateWeapon", true) addEventHandler("rotateWeapon", root, rotateWeapon)
  22. This is maybe a stupid question but maybe some one have a traffic objects map? or where it can be parsed? I have checkout an IDE, IPL files from original GTA:SA game, but i didn't found where it can be defined (dynamic traffic object with positon and rotation, i guess it maybe stored in gta3.img, right?). local aObjectIDs = { 3855; -- GAY_TRAFFIC_LIGHT 1262; -- MTraffic4 mitraffic 1263; -- MTraffic3 mitraffic 1283; -- MTraffic1 mitraffic 1284; -- MTraffic2 mitraffic 1315; -- trafficlight1 1350; -- CJ_TRAFFIC_LIGHT4 CJ_traffic 1351; -- CJ_TRAFFIC_LIGHT5 CJ_traffic 1352; -- CJ_TRAFFIC_LIGHT3 CJ_traffic }; I want to make a workaround to fix this issue: https://bugs.mtasa.com/view.php?id=9387 I Need check if vehicle near the traffic object and get object rotation.
  23. Сразу оговорюсь, данный урок требует основных знаний о таблицах Lua На самом деле в просторах сети полно учебников по данной теме, поэтому решил я написать этот учебник просто потому что его тут нет (естественно копировать всё из других учебников я не стану, а постараюсь рассказать своими словами) Зачем это нужно В целом, всё это, позволяет нам изменить поведение Lua в определённых ситуациях 1. Возможность реализации ООП в Lua 2. Перегрузка операторов (это так же может быть необходимым для П.1) Что это такое Метатаблица - это обычная таблица в которой описываются определённые события (например сложение, вычитание, сравнивание и т.д.) В качестве названия события выступает индекс таблицы, а её значение - обработчик события (метод) Как использовать Для использования достаточно просто обозначить таблице нашу мета-таблицу MyTable = {}; MyTableMeta = { __index = MyTable }; setmetatable( MyTable, MyTableMeta ); Методы нашей мета-таблицы можно определить в любое время, в силу для таблицы они вступают сразу после определения. Ниже список всех доступных событий и их описание __index( self, key ) чтение по ключу __newindex( self, key, value ) запись по ключу __call( self, ... ) вызов как функции __add( self, arg ) сложение __sub( self, arg ) вычитание __mul( self, arg ) умножение __div( self, arg ) деление __mod( self, arg ) остаток от деления __pow( self, arg ) возведение в степень __unm( self ) унарный минус __concat( self, arg ) конкатенация строк __len( self ) длина __eq( self, arg ) оператор "равно" __lt( self, arg ) оператор "меньше" __le( self, arg ) оператор "меньше или равно" __tostring( self ) Вызывается при попытке перевести объект в строковое представление (например с помощью функции tostring) __gc Вызывается для userdata-объектов при сборке мусора __metatable Если задать это поле в метатаблице, то getmetatable будет просто возвращать его значение, а setmetatable вернет ошибку. Пример Рассмотрим работу метатаблиц на примере события __call. Допустим мы хотим чтобы таблицу Vector3 можно было использовать как функцию. local Vector3 = {}; local Vector3_meta = { -- Добавляем наше событие __call = function( self, fX, fY, fZ ) -- self это указатель на нашу таблицу Vector3 return { X = fX, Y = fY, Z = fZ }; end; }; setmetatable( Vector3, Vector3_meta ); -- Устанавливаем метатаблицу для Vector3 Готово! Теперь если вызвать Vector3( 1, 2, 3 ) то нам вернётся новый объект - таблица с полями X, Y и Z. Теперь немного усложним задачу, дадим нашему объекту свою метатаблицу Vector3_meta_object = -- Это будет метатаблица для всех новых объектов { -- Добавляем событие сложения __add = function( vec1, vec2 ) -- vec1 - таблица слева, vec2 - таблица справа return Vector3( vec1.X + vec2.X, vec1.Y + vec2.Y, vec1.Z + vec2.Z ); -- Создаём новый объект end; }; Vector3 = {}; Vector3_meta = { __call = function( self, fX, fY, fZ ) local vecObject = { X = fX, Y = fY, Z = fZ }; setmetatable( vecObject, Vector3_meta_object ); -- Тут мы указываем метатаблицу нашему новому объекту return vecObject; end; }; setmetatable( Vector3, Vector3_meta ); -- Проверяем vec1 = Vector3( 12, 34, 56 ); vec2 = Vector3( 78, 90, 12 ); vec3 = vec1 + vec2; print( vec3.X, vec3.Y, vec3.Z ); -- 90 124 68 В итоге при сложении двух векторов (двух таблиц с этой метатаблицей), у нас получится новый объект с новыми X Y Z. print( vec3.X, vec3.Y, vec3.Z ); - На мой взгляд это немного не удобно, намного удобнее было бы просто передать вектор в функцию print, давайте исправим, для этого нам понадобится событие __tostring function Vector3_meta_object.__tostring( self ) return "( " .. self.X .. ", " .. self.Y .. ", " .. self.Z .. " )"; end -- Проверяем vec1 = Vector3( 12, 34, 56 ); vec2 = Vector3( 78, 90, 12 ); vec3 = vec1 + vec2; print( vec3 ); -- ( 90, 124, 68 ); Заключение Как видно на примерах, в этом нет ничего сложного. Как и говорилось выше, с помощью данного функционала можно реализовать полноценные классы. Есть пару библиотек которые автоматизируют этот процесс, одна из них идёт в комплекте с Lua (require "classlib"), а вторая валяется где-то тут. Задавайте свои вопросы, постараюсь на них ответить Материал написан специально для mtasa.com. Копирование запрещено
×
×
  • Create New...