# Difference between revisions of "AutoAttach"

This function attach an element into another by calculating the rotation and position offset automatically. It works exactly like attachElements but you don't need to provide offset parameters.

## Syntax

`bool autoAttach (element theElement, element theAttachToElement)`

### Required Arguments

• theElement: The element to be attached.
• theAttachToElement: The element to attach the first to.

### Returns

Returns true if the attaching process was successful, false otherwise.

## Code

Click to collapse [-]
Shared
```function autoAttach (theElement, theAttachToElement)
if (theElement and theAttachToElement) then
local mat = getElementMatrix (theAttachToElement)
local vec = Vector3 (getElementPosition(theElement))
local tx, ty, tz = getElementRotation (theAttachToElement)
local vx, vy, vz = getElementRotation (theElement)
local rotX, rotY, rotZ = 0, 0, 0
if (tx < vx) then
rotX = math.abs(tx - vx)
elseif (tx > vx) then
rotX = vx - tx
end
if (ty < vy) then
rotY = math.abs(ty - vy)
elseif (ty > vy) then
rotY = vy - ty
end
if (tz < vz) then
rotZ = math.abs(tz - vz)
elseif (tz > vz) then
rotZ = vz - tz
end

mat[1][4] = 0
mat[2][4] = 0
mat[3][4] = 0
mat[4][4] = 1
mat = matrix.invert (mat)

local offX = vec.x * mat[1][1] + vec.y * mat[2][1] + vec.z * mat[3][1] + mat[4][1]
local offY = vec.x * mat[1][2] + vec.y * mat[2][2] + vec.z * mat[3][2] + mat[4][2]
local offZ = vec.x * mat[1][3] + vec.y * mat[2][3] + vec.z * mat[3][3] + mat[4][3]

if (attachElements (theElement, theAttachToElement, offX, offY, offZ, rotX, rotY, rotZ)) then
return true
end
end
return false
end
```

Author: LordHenry

## Examples

Click to collapse [-]
Example1

This example attach a vehicle into another at the same position it is when the player uses the command /attach.
It also detach the vehicle if the command is used again.
This example creates a Packer (443) and a FCR-900 (521) at the center of the map. You need to be there to interact with them.

```theTruck = createVehicle (443, 0, 0, 4)
theVehicle = createVehicle (521, 0, 0, 7)

state = not state
if (state) then
autoAttach (theVehicle, theTruck)
outputChatBox ("Bike attached to the truck", thePlayer, 0, 255, 0)
else
detachElements (theVehicle, theTruck)
outputChatBox ("Bike detached from the truck", thePlayer, 255, 0, 0)
end
end)
```

Author: LordHenry

### Table functions

• addTableChangeHandler » This function monitors the changes of a table.
• getTableFromSql » This functionality is used to obtain saved tables using the function (SetTableToSql ).
• isValueInTable » This function returns true if the value exists in the table, false if the value does not exist in the table.
• pairsByKeys » This function sort pairs table.
• rangeToTable » This function converts a string range to a table containing number values.
• setTableProtected » This function protects a table and makes it read-only.
• setTableToSql » This function is used to save the table in the database (sql).
• Sort_Functions » These functions are able to sort your tables by a key.
• table.compare » This function checks whether two given tables are equal.
• table.copy » This function copies a whole table and all the tables in that table.
• table.deepmerge » This function deep merges two tables. Every nested table will be correspondingly merged.
• table.element » This function returns a new table with only userdata content.
• table.empty » This function checks whether a table is empty.
• table.fromString » This function converts string to a table.
• table.getRandomRows » This function returns random rows from table.
• table.map » This function goes through a table and replaces every field with the return of the passed function, where the field's value is passed as first argument and optionally more arguments.
• table.merge » This function merges two or more tables together.
• table.random » This function retrieves a random value from a table.
• table.removeValue » This function removes a specified value from a table.
• table.size » This function returns the absolute size of a table.
• table.toString » This function converts table to a string.
• table.toStringArray » This function converts array to a string.

### ACL functions

• aclGroupClone » This function clone a group to another group with/without ACLs and/or objects.
• getAccountsRanks » This function is used to detect the account name groups and put them in the chat.
• getPlayerAcls » This function returns a table of all ACL groups on a player.
• getPlayersInACLGroup » This function returns all players in an ACL group.
• isPlayerInACL » This function checks if a player element is in an ACL group.
• renameAclGroup » This function gives an existing ACL group a new name.

### Camera functions

• smoothMoveCamera » This function allows you to create a cinematic camera flight.

### Cursor functions

• getCursorMovedOn » This function checks in which way the cursor is currently moving.

### Effects functions

• attachEffect » This function allows you attach an effect to an element.

### Element functions

• autoAttach » This function attaches one element into another at the same position and rotation they are.
• isElementPlayer » This function checks whether the element is a player or not.
• attachElementToBone » This function allows you to attach an element to ped bone accurately using new bone functions.
• getElementsInDimension » This function returns a table of elements that are in the specified dimension.
• getElementSpeed » This function returns the specified element's speed in m/s, km/h or mph.
• getElementsWithinMarker » This function returns a table of elements that are within a marker's collision shape.
• getElementUsingData » This function returns table elements that contains the elements data with the given key and value.
• getNearestElement » This function returns the nearest element (of a specific type) to a player.
• isElementInPhotograph » This function checks if an element is in the player's camera picture area.
• isElementInRange » This function allows you to check if an element's range to a main point is within the maximum range.
• isElementMoving» This function checks if an element is moving.
• isElementWithinAColShape» This function checks if an element is within a collision shape element.
• isElementInAir» This function checks if an element is in air or not.
• multi_check » This function checks one element to many, handy and clean.
• setElementSpeed » This function allows you to set the speed of an element in kph or mph units.

### Events

• onVehicleWeaponFire » This code implements an event that is triggered when a player in a vehicle fires a vehicle's weapon.

### Input functions

• bindControlKeys » This function allows you to bind each key bound to a control individually. Doing this bypasses a little MTA restriction.
• getBoundControls » This function returns a table of control names that are bound to the specified key.
• unbindControlKeys » This function allows you to unbind each key bound to a control individually. Use this function with bindControlKeys.

### Data functions

• byte2human » This function converts an integer (number of bytes) into a human-readable unit.
• capitalize » This function capitalizes a given string.
• convertDate » This function converts date to another look.
• convertServerTickToTimeStamp » This function converts server ticks to a unix timestamp.
• convertTextToSpeech » This function converts the provided text to a speech in the provided language which players can hear.
• findRotation3D » This function takes two sets of XYZ coordinates. It returns the 3D direction from point A to point B.
• findRotation » This function takes two points and returns the direction from point A to point B.
• formatDate » This function formats a date on the basis of a format string and returns it.
• formatNumber » This function formats large numbers by adding commas.
• generateRandomASCIIString » This function returns a random string which uses ASCII characters.
• generateString » This function generates a random string with any characters.
• getAge » This function calculates the age of a given birthday.
• getDistance » Returns the distance between two elements.
• getDistanceBetweenElements » Esta funcion sirve para obtener la distancia entre dos elementos.
• getDistanceBetweenPointAndSegment2D » This function takes point coordinates and line (a segment) starting and ending coordinates. It returns the shortest distance between the point and the line.
• getEasterDate » This function returns easter date monthday and month for a given year.
• getFreeDimension » This function get free dimension.
• getKeyFromValueInTable » This function returns the key of the specified value in a table.
• getOffsetFromXYZ » This function allows you to take an entity and a position and calculate the relative offset between them accounting for rotations.
• getPointFromDistanceRotation » This function finds a point based on a starting point, direction and distance.
• getRealMonth » This function returns the current month name
• getRGColorFromPercentage »This function returns two integers representing red and green colors according to the specified percentage.
• getScreenRotationFromWorldPosition » This function returns a screen relative rotation to a world position.
• getTimestamp » This function returns the UNIX timestamp of a specified date and time.
• gradientString » This function transforms a string in a new coloured gradient string.
• hex2rgb » This function convert hex to rgb.
• hexColorToRGB » This function convert hex string/number to RGBA values.
• isLeapYear » This function returns a boolean representing if a given year is a leap year.
• isValidMail » This function checks whether a provided e-mail string is valid.
• removeHex » This function is used to remove hexadecimal numbers (colors, for example) from strings.
• RGBToHex » This function returns a string representing the color in hexadecimal.
• RGBToHSV » This function convert RGB to HSV color space.
• secondsToTimeDesc » This function converts a plain seconds-integer into a user-friendly time description.
• string.count » This function counts the amount of occurences of a string in a string.
• string.explode » This function splits a string at a given separator pattern and returns a table with the pieces.
• string.insert » This function inserts a string within another string at a given position.
• switch » This function allows the value of a variable or expression to control the flow of program execution via a multiway branch.
• tocolor2rgba » This function convert tocolor to rgba.
• toHex » This function converts a decimal number to a hexadecimal number, as a fix to be used client-side.
• var dump » This function outputs information about one or more variables using outputConsole.
• wavelengthToRGBA » This function converts a physical wavelength of light to a RGBA color.

### GUI functions

• centerWindow » This function centers a CEGUI window element responsively in any resolution.
• guiMoveElement » This function moves guiElement by/like using moveObject.
• guiSetStaticImageMovable » This function allows you to move a static image like a gui window.
• isMouseOnGUICloseButton » This function allows you to check whether the mouse cursor/pointer is within a gui-window's native close button.
• isMouseOnGuiElement » This function allows you to check whether or not your mouse is over a specific gui element, this is especially useful if the gui element has a parent.

### Math functions

• math.clamp » This function returns the number between range of numbers or it's minimum or maximum.
• math.getBezierPoint » Get N-th order bezier point.
• math.hypot » This function returns the Hypotenuse of the triangle given by sides x and y.
• math.isPointInPolygon » Check if point is inside polygon or not.
• math.lerp » Get val between two integer.
• math.percent » This function returns a percentage from two number values.
• math.polygonArea » Compute area of any polygon.
• math.randomDiff » Generates a pseudo-random integer that's always different from the last random number generated.
• math.rotVecToEulerAngle » Rotation Vector To Euler Angle
• math.round » Rounds a number whereas the number of decimals to keep and the method may be set.
• mathNumber » This function is a workaround for the client-side floating-point precision of 24-bits.
• reMap » Re-maps a number from one range to another.
• math.percentProgress » Returns a percentage progress from two specific values.
• math.average » This function returns the simple arithmetic mean of multiple numbers.

### Ped functions

• getAlivePlayers » This function returns a table of the alive players client-side.
• getAlivePlayersInTeam » This function returns a table of the alive players in a team.
• getGuestPlayers » This function gets a players not login or players Guest .
• getOnlineAdmins » This function returns a table of all logged-in administrators.
• getPedEyesPosition » This function allows you to get peds eyes position.
• getPedGender » This function allows you to get peds their gender.
• getPedMaxHealth » This function returns a pedestrians's maximum health by converting it from their maximum health stat.
• getPedMaxOxygenLevel » This function returns a ped's maximum oxygen level by converting it from their maximum underwater stamina stat.
• getPedWeaponSkill » This function returns a ped's corresponding weapon skill level name.
• getPedHitBone » This function gets the approximate number of the bone where the ped is hit.
• getPlayerFromNamePart » This function returns a player from partial name.
• getPlayerFromSerial » This function returns a player from their serial.
• getPlayersByData » This function returns a table of players that have the specified data name.
• getPlayersInPhotograph » This function returns a table of all players in photograph.
• getPlayersInVehicles » This function returns a table of the players insides vehicles from a specified dimension.
• isPedAiming» This function checks if a pedestrian is aiming their weapon.
• isPedAimingNearPed » This is similar to isPedAiming but uses a colshape to be more precise.
• isPedDiving » This feature checks that pedestrian is diving in the water.
• isPedDrivingVehicle » This function checks if a specified pedestrian is driving a vehicle.
• isPlayerInTeam » This function checks if a player is in a specified team.
• setPedAttack » This function will make a ped attack a specified target.
• setPedFollow » This function will make a ped follow a specified target.
• getPlayerNameFromID » This function will get the player name from the ID element data.

### Browser functions

• playVideo » This function plays a video on the screen.

### XML functions

• getXMLNodes » This function returns all children of a XML node.

### Utility

• animate » This function allows you to use interpolateBetween without render event and easily used.
• callClientFunction » This function allows you to call any client-side function from the server's side.
• callServerFunction » This function allows you to call any server-side function from the client's side.
• check » This function checks if its arguments are of the right type and calls the error-function if one is not.
• checkPassiveTimer » This function allows you to use passive timers in your conditions. For example you want to prevent players r

epeatedly using a command.

• coroutine.resume » This function applies a fix for hidden coroutine error messages.
• compact » This function create table containing variables and their values.
• getBanFromName » This functions returns the ban of the given playername.
• getCurrentFPS » This function returns the frames per second at which GTA: SA is running.
• getSkinNameFromID » This function returns the name of the skin from the given id.
• IfElse » This function returns one of two values based on a boolean expression.
• isCharInString » This shared function allows you to check if a char specified is in a string value.
• isMouseInCircle » This function checks if a cursor position is in circular area or not.
• isMouseInPosition » This function allows you to check whether the mouse cursor/pointer is within a rectangular position.
• iterElements » This function returns a time-saving iterator for your for-loops.
• PlotTrajectoryAtTime » Calculate projectile/water trajectory.
• preprocessor » This function allow you to use gcc macros.
• vector3:compare » This method checks whether two vectors match, with optional precision.
• svgCreateRoundedRectangle » This function creates a rectangle with rounded edges.