CreateVehicle: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
(Finally someone bothered to check the useless bDirection argument)
mNo edit summary
(17 intermediate revisions by 14 users not shown)
Line 1: Line 1:
__NOTOC__
__NOTOC__
{{Server client function}}
{{Server client function}}{{Note|Vehicles (and other elements) created client-side are only seen by the client that created them, aren't synced and players cannot enter them. They are essentially for display only.}}
{{note_box|Vehicles (and other elements) created client-side are only seen by the client that created them, aren't synced and players cannot enter them. They are essentially for display only.}}
This function creates a vehicle at the specified location.
This function creates a vehicle at the specified location.


Its worth noting that the position of the vehicle is the center point of the vehicle, not its base. As such, you need to ensure that the z value (vertical axis) is some height above the ground. You can find the exact height using the client side function [[getElementDistanceFromCentreOfMassToBaseOfModel]], or you can estimate it yourself and just spawn the vehicle so it drops to the ground.
Its worth nothing that the position of the vehicle is the center point of the vehicle, not its base. As such, you need to ensure that the z value (vertical axis) is some height above the ground. You can find the exact height using the client side function [[getElementDistanceFromCentreOfMassToBaseOfModel]], or you can estimate it yourself and just spawn the vehicle so it drops to the ground.
 


==Syntax==
==Syntax==
Line 24: Line 22:
* '''ry''': A floating point number representing the rotation about the Y axis in degrees.
* '''ry''': A floating point number representing the rotation about the Y axis in degrees.
* '''rz''': A floating point number representing the rotation about the Z axis in degrees.
* '''rz''': A floating point number representing the rotation about the Z axis in degrees.
* '''numberplate''': A string that will go on the number plate of the car (max 8 characters). This is only applicable to cars.
* '''numberplate''': A string that will go on the number plate of the vehicle (max 8 characters).
* '''bDirection''' ''(serverside only)'': Currently this boolean has no effect, but it's read by the code. If ''true'', the train would move clockwise. If ''false'', it would travel counterclockwise. <!-- See https://github.com/multitheftauto/mtasa-blue/blob/master/MTA10_Server/mods/deathmatch/logic/CStaticFunctionDefinitions.cpp#L4817 for source code that proves this -->
* '''bDirection''' ''(serverside only)'': Placeholder [[boolean]] which provides backward compatibility with some scripts. It never had any effect, but it is read by the code. It is recommended to ignore this argument, passing ''false'' or the ''variant1'' argument in its place.
{{New feature/item|3.0120|1.2||  
{{New feature/item|3.0120|1.2||  
* '''variant1''': An integer for the first vehicle variant see [[Vehicle variants]]
* '''variant1''': An integer for the first vehicle variant. See [[vehicle variants]].
* '''variant2''': An integer for the second vehicle variant see [[Vehicle variants]]
* '''variant2''': An integer for the second vehicle variant. See [[vehicle variants]].
}}
}}


Line 35: Line 33:


==Using trains==
==Using trains==
Trains are created using the createVehicle function. They are placed at the nearest point of the GTASA train pathing (railroad tracks) from their spawning point.  
Trains are created using the createVehicle function. They are placed at the nearest point of the GTASA train pathing (they usually are railroad tracks) from their spawning point.


==Example==
==Example==
<section name="Example 1: Server" class="server" show="true">
<section name="Example 1: Server" class="server" show="true">
This script spawns a Rhino on top of one lucky individual.
This example creates a 'vehicle spawner' marker that gives the player a vehicle as soon they step into it.
<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
function scriptCreateTank ( player, command )
local vehMark = createMarker(-2426.34106, -639.12714, 132.93631,"cylinder")
      local luckyBugger = getRandomPlayer() -- get a random player
 
      local x, y, z = getElementPosition ( luckyBugger ) -- retrive the player's position
function vehicleSpawner(hitElement,matchingDimension)
      createVehicle ( 432, x, y, z + 10 ) -- create the tank 10 units above them
if getElementType(hitElement) == "player" then
      outputChatBox ( "You got Tank'd!", luckyBugger )
if getPedOccupiedVehicle(hitElement) == false then
end
local x,y,z = getElementPosition(hitElement)
--Attach the 'scriptCreateTank' function to the "tank" command
local veh = createVehicle(551, x,y,z)
addCommandHandler ( "tank", scriptCreateTank )
warpPedIntoVehicle(hitElement,veh)
end
end  
end
addEventHandler("onMarkerHit",vehMark,vehicleSpawner)
</syntaxhighlight>
</syntaxhighlight>
</section>
</section>


<section name="Example 2: Server" class="server" show="true">
<section name="Example 2: Server" class="server" show="true">
This example spawns a car.
To spawn a car need to enter the number of the desired car and also specify the coordinates for the spawn point of this car.
<syntaxhighlight lang="lua">
-- Cars with this ID is not allowed
LockID = {
[435] = true ;
[441] = true ;
[449] = true ;
[450] = true ;
[464] = true ;
[465] = true ;
[501] = true ;
[537] = true ;
[538] = true ;
[564] = true ;
[569] = true ;
[570] = true ;
[584] = true ;
[590] = true ;
[591] = true ;
[594] = true ;
[606] = true ;
[607] = true ;
[608] = true ;
[610] = true ;
[611] = true ;
}
addCommandHandler("spveh", function(p, command, idmodel, sx, sy, sz, numberplate)
  if getElementType(p) == "player" then
  if ( tonumber(idmodel) ) and ( tonumber(sx) ) and ( tonumber(sy) ) and ( tonumber(sz) ) then
  if (not LockID[tonumber(idmodel)] ) then
            data = ( numberplate or "PRIVATE" )
            local spawn = createVehicle(tonumber(idmodel), tonumber(sx), tonumber(sy), tonumber(sz), 0, 0, 0, data)
            if isElement(spawn) then -- If the vehicle has been created then:
            outputChatBox("Your vehicle has been created! INFO:", p, 255, 255, 0)
            outputChatBox("ID Vehicle: "..getElementModel(spawn), p, 255, 255, 0)
            outputChatBox("Name Vehicle: "..getVehicleName(spawn), p, 255, 255, 0)
            local x, y, z = getElementPosition(spawn) -- Check the vehicle position
            outputChatBox("Vehicle Coordinates: X: "..tostring(x) .. ", Y: " .. tostring(y) .. ", Z: " .. tostring(z), p, 255, 255, 0)
            outputChatBox("Vehicle Number plate: "..getVehiclePlateText(spawn), p, 255, 255, 0)
    else
        outputChatBox("Unknown ERROR!", p, 255, 100, 100)
        end
    else
        outputChatBox("Sorry! This car model number is not allowed!", p, 255, 100, 100)
        end
    else
        outputChatBox("Error! Correct syntax Use: /spveh [model] [x] [y] [z]", p, 255, 100, 100)
        outputChatBox("Or /spveh [model] [x] [y] [z] [Number Plate]", p, 255, 100, 100)
      end
  end
end)
</syntaxhighlight>
</section>
<section name="Example 3: Client" class="client" show="true">
This script spawns a Rhino on top of the local player.
<syntaxhighlight lang="lua">
function scriptCreateTank ( commandName )
      local luckyBugger = getLocalPlayer() -- get the local player
      local x, y, z = getElementPosition ( luckyBugger ) -- retrive the player's position
      createVehicle ( 432, x, y, z + 10 ) -- create the tank 10 units above them
      outputChatBox ( "You got Tank'd!", 255, 0, 0)
end
--Attach the 'scriptCreateTank' function to the "tank" command
addCommandHandler ( "tank", scriptCreateTank )
</syntaxhighlight>
</section>
<section name="Example 4: Server" class="server" show="false">
This example creates a vehicle five units to the right of a player when they type ''createvehicle'' and its name in the console:
This example creates a vehicle five units to the right of a player when they type ''createvehicle'' and its name in the console:
<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
Line 135: Line 66:
       -- calculate the position of the vehicle based on the player's position and rotation:
       -- calculate the position of the vehicle based on the player's position and rotation:
       local x, y, z = getElementPosition ( sourcePlayer ) -- get the player's position
       local x, y, z = getElementPosition ( sourcePlayer ) -- get the player's position
       local rotZ = getPedRotation ( sourcePlayer ) -- get the player's rotation around the Z axis in degrees
       local rotZ = getElementRotation ( sourcePlayer ) -- get the player's rotation around the Z axis in degrees
       x = x + ( ( math.cos ( math.rad ( rotZ ) ) ) * distance ) -- calculate the X position of the vehicle
       x = x + ( ( math.cos ( math.rad ( rotZ ) ) ) * distance ) -- calculate the X position of the vehicle
       y = y + ( ( math.sin ( math.rad ( rotZ ) ) ) * distance ) -- calculate the Y position of the vehicle
       y = y + ( ( math.sin ( math.rad ( rotZ ) ) ) * distance ) -- calculate the Y position of the vehicle
Line 157: Line 88:
-- Attach the 'consoleCreateVehicle' function to the "createvehicle" command
-- Attach the 'consoleCreateVehicle' function to the "createvehicle" command
addCommandHandler ( "createvehicle", consoleCreateVehicle )
addCommandHandler ( "createvehicle", consoleCreateVehicle )
</syntaxhighlight>
</section>
<section name="Example 3: Server" class="server" show="false">
This script spawns a Rhino on top of one lucky individual.
<syntaxhighlight lang="lua">
function scriptCreateTank ( player, command )
      local luckyBugger = getRandomPlayer() -- get a random player
      local x, y, z = getElementPosition ( luckyBugger ) -- retrive the player's position
      createVehicle ( 432, x, y, z + 10 ) -- create the tank 10 units above them
      outputChatBox ( "You got Tank'd!", luckyBugger )
end
--Attach the 'scriptCreateTank' function to the "tank" command
addCommandHandler ( "tank", scriptCreateTank )
</syntaxhighlight>
</section>
<section name="Example 4: Server" class="server" show="false">
This example adds a ''/spveh'' command to spawn a car model in the provided coordinates. If any car created by this command gets blown up, it will respawn where it was created.
<syntaxhighlight lang="lua">
-- Do not allow the following IDs to be spawned
local forbiddenCars = { [435] = true, [441] = true, [449] = true, [450] = true, [464] = true, [465] = true, [501] = true,
                        [537] = true, [538] = true, [564] = true, [569] = true, [570] = true, [584] = true, [590] = true,
                        [591] = true, [594] = true, [606] = true, [607] = true, [608] = true, [610] = true, [611] = true }
local cmdVehRoot = createElement("commandVehicles") -- Dummy element containing the cars that this command has created
addCommandHandler("spveh",
    function(player, cmd, modelID, x, y, z, platetext)
        -- Check whether arguments are correct
        local modelID, x, y, z = tonumber(modelID), tonumber(x), tonumber(y), tonumber(z)
        if modelID and x and y and z then
            -- Do not continue if we shouldn't
            if forbiddenCars[modelID] then
                outputChatBox("The car model you provided is not allowed.", player, 255, 0, 0)
                return
            end
            local platetext = type(platetext) == "string" and platetext or "PRIVATE"
            -- Create the actual vehicle and set it as a children of our dummy element
            setElementParent(createVehicle(modelID, x, y, z, 0, 0, 0, platetext), cmdVehRoot)
            -- Inform the player about what we did
            outputChatBox("You have created a " .. getVehicleNameFromModel(modelID) .. " (model ID: " .. modelID .. ") at " .. table.concat({ x, y, z }, ", ") .. " with numberplate " .. platetext .. " successfully.", player, 0, 255, 0)
        else
            outputChatBox("Syntax: /" .. cmd .. " (modelID) (x) (y) (z) [numberplate]", player, 255, 255, 255)
        end
    end
)
-- If a vehicle that has been created using the command blows up, respawn it where it was created
addEventHandler("onVehicleExplode", cmdVehRoot,
    function()
        respawnVehicle(source)
    end
)
</syntaxhighlight>
</section>
<section name="Example 5: Client" class="client" show="true">
This script spawns a Rhino on top of the local player.
<syntaxhighlight lang="lua">
function scriptCreateTank ( commandName )
      local x, y, z = getElementPosition ( localPlayer ) -- retrive the player's position
      createVehicle ( 432, x, y, z + 10 ) -- create the tank 10 units above them
      outputChatBox ( "You got Tank'd!", 255, 0, 0)
end
--Attach the 'scriptCreateTank' function to the "tank" command
addCommandHandler ( "tank", scriptCreateTank )
</syntaxhighlight>
</syntaxhighlight>
</section>
</section>




{{New items|4.0132|1.4|
{{New items|3.0132|1.4|
This is an example of how this function is executed in an OOP environment.
This is an example of how this function is executed in an OOP environment.
<section name="OOP server" class="server" show="true">
<section name="OOP server" class="server" show="true">
Line 190: Line 187:


{{Vehicle functions}}
{{Vehicle functions}}
[[de:createVehicle]]
[[pl:createVehicle]]
[[ru:CreateVehicle]]
[[pt-br:CreateVehicle]]

Revision as of 18:38, 6 August 2020

[[{{{image}}}|link=|]] Note: Vehicles (and other elements) created client-side are only seen by the client that created them, aren't synced and players cannot enter them. They are essentially for display only.

This function creates a vehicle at the specified location.

Its worth nothing that the position of the vehicle is the center point of the vehicle, not its base. As such, you need to ensure that the z value (vertical axis) is some height above the ground. You can find the exact height using the client side function getElementDistanceFromCentreOfMassToBaseOfModel, or you can estimate it yourself and just spawn the vehicle so it drops to the ground.

Syntax

vehicle createVehicle ( int model, float x, float y, float z [, float rx, float ry, float rz, string numberplate, bool bDirection, int variant1, int variant2 ] )

OOP Syntax Help! I don't understand this!

Method: Vehicle(...)


Required Arguments

  • model: The vehicle ID of the vehicle being created.
  • x: A floating point number representing the X coordinate on the map.
  • y: A floating point number representing the Y coordinate on the map.
  • z: A floating point number representing the Z coordinate on the map.

Optional Arguments

NOTE: When using optional arguments, you might need to supply all arguments before the one you wish to use. For more information on optional arguments, see optional arguments.

  • rx: A floating point number representing the rotation about the X axis in degrees.
  • ry: A floating point number representing the rotation about the Y axis in degrees.
  • rz: A floating point number representing the rotation about the Z axis in degrees.
  • numberplate: A string that will go on the number plate of the vehicle (max 8 characters).
  • bDirection (serverside only): Placeholder boolean which provides backward compatibility with some scripts. It never had any effect, but it is read by the code. It is recommended to ignore this argument, passing false or the variant1 argument in its place.

Returns

Returns the vehicle element that was created. Returns false if the arguments are incorrect, or if the vehicle limit of 65535 is exceeded.

Using trains

Trains are created using the createVehicle function. They are placed at the nearest point of the GTASA train pathing (they usually are railroad tracks) from their spawning point.

Example

Click to collapse [-]
Example 1: Server

This example creates a 'vehicle spawner' marker that gives the player a vehicle as soon they step into it.

local vehMark = createMarker(-2426.34106, -639.12714, 132.93631,"cylinder")

function vehicleSpawner(hitElement,matchingDimension)
	if getElementType(hitElement) == "player" then
		if getPedOccupiedVehicle(hitElement) == false then
		local x,y,z = getElementPosition(hitElement)
			local veh = createVehicle(551, x,y,z)
			warpPedIntoVehicle(hitElement,veh)
		end
	end 
end 
addEventHandler("onMarkerHit",vehMark,vehicleSpawner)
Click to collapse [-]
Example 2: Server

This example creates a vehicle five units to the right of a player when they type createvehicle and its name in the console:

local distance = 5 --units

-- define our handler (we'll take a variable number of parameters where the name goes, because there are vehicle names with more than one word)
function consoleCreateVehicle ( sourcePlayer, commandName, ... )
   -- if a player triggered it, not the admin,
   if ( sourcePlayer ) then
      -- calculate the position of the vehicle based on the player's position and rotation:
      local x, y, z = getElementPosition ( sourcePlayer ) -- get the player's position
      local rotZ = getElementRotation ( sourcePlayer ) -- get the player's rotation around the Z axis in degrees
      x = x + ( ( math.cos ( math.rad ( rotZ ) ) ) * distance ) -- calculate the X position of the vehicle
      y = y + ( ( math.sin ( math.rad ( rotZ ) ) ) * distance ) -- calculate the Y position of the vehicle

      -- get the complete vehicle name by joining all passed parameters using Lua function table.concat
      local vehicleName = table.concat({...}, " ")
      -- get the vehicle's model ID from the name
      local vehicleID = getVehicleModelFromName ( vehicleName )
      -- if vehicle ID is valid,
      if vehicleID then
            -- create the vehicle using the information gathered above:
            local newVehicle = createVehicle ( vehicleID, x, y, z, 0, 0, rotZ )
            -- if vehicle creation failed, give the player a message
            if not newVehicle then
               outputConsole ( "Failed to create vehicle.", sourcePlayer )
            end
      end
   end
end

-- Attach the 'consoleCreateVehicle' function to the "createvehicle" command
addCommandHandler ( "createvehicle", consoleCreateVehicle )
Click to expand [+]
Example 3: Server
Click to expand [+]
Example 4: Server
Click to collapse [-]
Example 5: Client

This script spawns a Rhino on top of the local player.

function scriptCreateTank ( commandName )
      local x, y, z = getElementPosition ( localPlayer ) -- retrive the player's position
      createVehicle ( 432, x, y, z + 10 ) -- create the tank 10 units above them
      outputChatBox ( "You got Tank'd!", 255, 0, 0)
end
--Attach the 'scriptCreateTank' function to the "tank" command
addCommandHandler ( "tank", scriptCreateTank )


This is an example of how this function is executed in an OOP environment.

Click to collapse [-]
OOP server

This script will create an Infernus at the center (0, 0, 3) of San Andreas upon execution.

addEventHandler( "onResourceStart", resourceRoot,
    function()
        infernus = Vehicle(411, Vector3(0, 0, 3)); -- Create an Infernus and spawn it at the middle of SA.
        infernus:setColor(0, 0, 0); -- Set its color to black.
        infernus.damageProof = true; -- Make it damage proof
    end
)
	
addCommandHandler( "blowinfernus",
    function(p)
        if not infernus.blown then -- Check if the Infernus is blown up or not.
            infernus:blow();
        else -- Ouch, it's blown up, let's output an error to the player.
            outputChatBox( "The Infernus has already been blown up by you.", p, 255, 0, 0, false );
        end
    end)

See Also