📅  最后修改于: 2023-12-03 14:47:06.454000             🧑  作者: Mango
In Roblox Lua, Vector3
is a data type used to represent a position or a direction in 3D space. It is commonly used in game development for various purposes such as movement, collision detection, and camera manipulation.
To create a Vector3
object, you can use the constructor syntax:
local v = Vector3.new(x, y, z)
Where x
, y
, and z
are the respective coordinates of the vector.
Alternatively, you can use the Vector3
static methods Vector3.FromNormalId
and Vector3.FromAxis
to create predefined vectors:
local upVector = Vector3.FromNormalId(Enum.NormalId.Top)
local rightVector = Vector3.FromAxis(Vector3.new(0, 0, 1), math.pi / 2)
The Vector3
data type provides several useful properties:
X
: the X-coordinate of the vector.Y
: the Y-coordinate of the vector.Z
: the Z-coordinate of the vector.Magnitude
: the magnitude (length) of the vector.Unit
: returns a Vector3
with the same direction as the original vector, but with a magnitude of 1.Normalized
: returns a Vector3
with the same direction as the original vector, but with a magnitude of 1
.local v = Vector3.new(1, 2, 3)
print(v.X) -- 1
print(v.Magnitude) -- 3.74165
print(v.Unit) -- 0.267261, 0.534522, 0.801784
Vector3
supports several arithmetic operations:
+
: adds two vectors.-
: subtracts two vectors.*
: multiplies a vector by a scalar./
: divides a vector by a scalar.local v1 = Vector3.new(1, 2, 3)
local v2 = Vector3.new(4, 5, 6)
local v3 = v1 + v2 -- 5, 7, 9
local v4 = v3 / 3 -- 1.66667, 2.33333, 3
Vector3
also supports the following operations:
Dot
: returns the dot product of two vectors.Cross
: returns the cross product of two vectors.Lerp
: returns a Vector3
interpolated between two vectors.Angle
: returns the angle between two vectors.ProjectOn
: returns the projection of a vector onto another vector.local v1 = Vector3.new(1, 2, 3)
local v2 = Vector3.new(4, 5, 6)
local dotProduct = v1.Dot(v2) -- 32
local crossProduct = v1.Cross(v2) -- -3, 6, -3
local lerp = v1.Lerp(v2, 0.5) -- 2.5, 3.5, 4.5
local angle = v1.Angle(v2) -- 0.225726
local projection = v1.ProjectOn(v2) -- 2.11099, 2.63874, 3.16649
Vector3
is an indispensable data type in Roblox Lua game development. With its many useful properties and operations, it can be used to implement a wide range of gameplay mechanics.