Vector/Vector3: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
m (Restructure)
(Added documentation for the dotproduct and normalize)
Line 28: Line 28:
===cross===
===cross===
===dot===
===dot===
Calculates the (standard) dot/scalar product. This can be used to calculate the angle between two vectors. If the standard scalar product is 0, both vectors are orthogonal.
<section name="Shared" class="both" show="true">
<syntaxhighlight lang="lua">
local vec1 = Vector3(1, 0, 0)
local vec2 = Vector3(0, 0, 0)
local dotproduct = vec1:dot(vec2)
if dotproduct == 0 then
    outputDebugString("vec1 is orthogonal to vec2")
end
-- Calculate angle between vec1 and vec2
function angle(vec1, vec2)
    -- Calculate the angle by applying law of cosines
    return math.acos(vec1:dot(vec2)/(vec1.length*vec2.length)
end
outputDebugString("Angle between vec1 and vec2: "..math.deg(angle(vec1, vec2)).."°")
</syntaxhighlight>
</section>
===normalize===
===normalize===
Converts the vector to a unit vector (a vector of length 1).


===getX and setX===
===getX and setX===

Revision as of 20:55, 3 February 2015

The vector3 class represents a three-dimensional vector.

Methods

create

This is default constructor for the Vector3 class and returns a Vector3 object.

Syntax

vector3 Vector3 ( float x = 0, float y = 0, float z = 0 )
  • x, y and z: coordinates for the vector. If not specified, they default to 0.
  • Instead of these three coordinates, a single Vector3 object may be inserted to clone it.

Example

This example sorts all players in a nice line on the center of the map.

Click to collapse [-]
Shared
local players = getElementsByType("player")
local newPlayerPosition = Vector3(-#players - 1, 0, 10) -- Initialize the position vector for the first player in the list
for _, player in ipairs(players) do
    -- Move each player 1 unit forward in X from the previous one
    newPlayerPosition.x = newPlayerPosition.x + 1
    setElementPosition(player, newPlayerPosition)
end

cross

dot

Calculates the (standard) dot/scalar product. This can be used to calculate the angle between two vectors. If the standard scalar product is 0, both vectors are orthogonal.

Click to collapse [-]
Shared
local vec1 = Vector3(1, 0, 0)
local vec2 = Vector3(0, 0, 0)
local dotproduct = vec1:dot(vec2)

if dotproduct == 0 then
    outputDebugString("vec1 is orthogonal to vec2")
end

-- Calculate angle between vec1 and vec2
function angle(vec1, vec2)
    -- Calculate the angle by applying law of cosines
    return math.acos(vec1:dot(vec2)/(vec1.length*vec2.length)
end

outputDebugString("Angle between vec1 and vec2: "..math.deg(angle(vec1, vec2)).."°")

normalize

Converts the vector to a unit vector (a vector of length 1).

getX and setX

getY and setY

getZ and setZ

getNormalized

getSquaredLength

getLength