跳至正文
版本:最新版 - a1.156.0 ⚖️

追踪与光线投射

如何在运行时使用追踪与光线投射来获取世界信息。

追踪提供了一种在地图中进行延伸并获取线段上存在何种物体的反馈的方法。使用它们时,你需要提供两个端点(起点和终点位置),物理系统会在这些点之间“追踪”一条线段,并报告它击中的任何 Actor。追踪与其他软件套件中的光线投射或光线追踪本质上是相同的。

信息

Traces are only available on the Client side, as the server doesn't run the physics of the world. If the server needs the result, send it through a Remote Event (and validate it, as the client could send anything).

以下示例将向你展示如何获取玩家正在注视的物体以及注视的位置。

Client/Index.lua
-- Traces at each 100ms
Timer.SetInterval(function()
-- Gets the middle of the screen
local viewport_2D_center = Viewport.GetViewportSize() / 2

-- Deprojects to get the 3D Location for the middle of the screen
local viewport_3D = Viewport.DeprojectScreenToWorld(viewport_2D_center)

-- Makes a trace with the 3D Location and it's direction multiplied by 5000
-- Meaning it will trace 5000 units in that direction
local trace_max_distance = 5000

local start_location = viewport_3D.Position
local end_location = viewport_3D.Position + viewport_3D.Direction * trace_max_distance

-- Determine at which object we will be tracing for (WorldStatic - StaticMeshes - and PhysicsBody - Props)
local collision_trace = CollisionChannel.WorldStatic | CollisionChannel.PhysicsBody

-- Sets the trace modes (we want it to return Entity and Draws a Debug line)
local trace_mode = TraceMode.ReturnEntity | TraceMode.DrawDebug

-- Does the trace. TraceMode.DrawDebug makes it draw a Debug Line in the traced segment
local trace_result = Trace.LineSingle(start_location, end_location, collision_trace, trace_mode)

-- If hit something draws a Debug Point at the location
if (trace_result.Success) then

-- Makes the point Red or Green if hit an Actor
local color = Color(1, 0, 0) -- Red

if (trace_result.Entity) then
color = Color(0, 1, 0) -- Green

-- Here you can check which actor you hit like
-- if (trace_result.Entity:IsA(Character)) then ...
end

-- Draws a Debug Point at the Hit location for 5 seconds with size 10
Debug.DrawPoint(trace_result.Location, color, 5, 10)
end
end, 100)
提示

正如你所见,我们可以向 Trace 传递按位运算符,以便一次追踪多个 CollisionChannel!在 CollisionChannels 之间使用 | 即可实现此目的。

Other Trace Shapes​

Besides lines, it is also possible to trace with shapes, which is useful to check if something fits somewhere or to detect things in an area. All of them have a Single version (returns the first hit) and a Multi version (returns all hits):

ShapeSingleMulti
LineTrace.LineSingle()Trace.LineMulti()
SphereTrace.SphereSingle()Trace.SphereMulti()
BoxTrace.BoxSingle()Trace.BoxMulti()
CapsuleTrace.CapsuleSingle()Trace.CapsuleMulti()
提示

The result table only includes some fields (like Entity or SurfaceType) if you ask for them with the matching TraceMode flags, such as TraceMode.ReturnEntity or TraceMode.ReturnPhysicalMaterial.