경로 탐색은 캐릭터나 객체(에이전트)가 장애물을 피해 목적지에 도달하기 위해 논리적 경로를 따라 이동하는 과정으로, 선택적으로 위험한 물질이나 정의된 지역을 피할 수 있습니다.
내비게이션 시각화
경로 탐색 레이아웃 및 디버깅을 지원하기 위해, 스튜디오는 내비게이션 메시와 수정자 레이블을 렌더링할 수 있습니다. 이를 활성화하려면 3D 뷰포트의 오른쪽 상단 모서리에 있는 시각화 옵션 위젯에서 내비게이션 메시와 경로 탐색 수정자를 켭니다.

내비게이션 메시가 활성화되면, 색상으로 표시된 영역이 캐릭터가 걷거나 수영할 수 있는 곳을 보여줍니다. 작은 화살표는 캐릭터가 점프하여 도달하려고 시도할 영역을 나타냅니다.

구현
경로 탐색은 PathfindingService와 CreatePath()와 같은 관련 메서드를 통해 다양한 방식으로 구현할 수 있지만, 이 섹션에서는 플레이어의 캐릭터를 위한 다음 경로 탐색 스크립트를 사용합니다.
읽으면서 테스트하려면:
- 중요탐색기에서 StarterPlayer 컨테이너를 선택합니다. 그런 다음 속성 창에서 DevComputerMovementMode와 DevTouchMovementMode를 모두 Scriptable로 설정합니다.


다음 코드를 LocalScript에 복사하여 StarterCharacterScripts 내에 붙여넣거나 이 패키지를 가져와 StarterCharacterScripts에 드롭합니다.
PlayerPathFollow (LocalScript in StarterCharacterScripts)local PathfindingService = game:GetService("PathfindingService")local Players = game:GetService("Players")local RunService = game:GetService("RunService")local DESTINATION = Vector3.new(20, 0.5, 20)local GROUND_WAIT = 0.01local VELOCITY_MULTIPLIER = 0.0625local path = PathfindingService:CreatePath({AgentCanClimb = true,Costs = {Water = 20}})local character = script.Parentlocal humanoid = character:WaitForChild("Humanoid")local waypointslocal nextWaypointIndexlocal blockedConnectionlocal currentWaypointReachedConnectionlocal currentWaypointPlaneNormal = Vector3.zerolocal currentWaypointPlaneDistance = 0local pathfinderWorking = falselocal function disconnectCurrentWaypointReachedConnection()if not currentWaypointReachedConnection then return endcurrentWaypointReachedConnection:Disconnect()currentWaypointReachedConnection = nilendlocal function isCurrentWaypointReached()if humanoid.FloorMaterial == Enum.Material.Air thenreturn falseendlocal reached = falseif currentWaypointPlaneNormal ~= Vector3.zero then-- Compute the distance from humanoid to destination planelocal dist = currentWaypointPlaneNormal:Dot(humanoid.RootPart.Position) - currentWaypointPlaneDistance-- Compute the component of the humanoid velocity that is towards the planelocal velocity = -currentWaypointPlaneNormal:Dot(humanoid.RootPart.Velocity)-- Compute the threshold from the destination plane based on humanoid velocitylocal threshold = math.max(1.0, VELOCITY_MULTIPLIER * velocity)-- Consider waypoint reached if less then threshold in front of the planereached = dist < thresholdelsereached = trueendif reached thencurrentWaypointPlaneNormal = Vector3.zerocurrentWaypointPlaneDistance = 0moveToNextWaypoint()endendlocal function calculateNextWaypointApproach()nextWaypointIndex += 1if nextWaypointIndex > #waypoints thenreturn falseendlocal currentWaypoint = waypoints[nextWaypointIndex - 1]local nextWaypoint = waypoints[nextWaypointIndex]-- Build destination plane from next waypoint towards current onecurrentWaypointPlaneNormal = currentWaypoint.Position - nextWaypoint.Position-- Set normal perpendicular to Y plane when not climbing upif nextWaypoint.Label ~= "Climb" thencurrentWaypointPlaneNormal = Vector3.new(currentWaypointPlaneNormal.X, 0, currentWaypointPlaneNormal.Z)endif currentWaypointPlaneNormal.Magnitude > 0.000001 thencurrentWaypointPlaneNormal = currentWaypointPlaneNormal.UnitcurrentWaypointPlaneDistance = currentWaypointPlaneNormal:Dot(nextWaypoint.Position)endreturn trueendlocal function resetWaypointData()humanoid:Move(Vector3.zero)currentWaypointPlaneNormal = Vector3.zerocurrentWaypointPlaneDistance = 0disconnectCurrentWaypointReachedConnection()pathfinderWorking = falseendlocal function waitForGround()while humanoid.FloorMaterial == Enum.Material.Air dotask.wait(GROUND_WAIT)endendfunction moveToNextWaypoint()if calculateNextWaypointApproach() thendisconnectCurrentWaypointReachedConnection()currentWaypointReachedConnection = RunService.Heartbeat:Connect(isCurrentWaypointReached)local nextWaypointPosition = waypoints[nextWaypointIndex].Positionlocal nextWaypointAction = waypoints[nextWaypointIndex].Actionhumanoid:Move(nextWaypointPosition - humanoid.RootPart.Position)if waypoints[nextWaypointIndex + 1] and waypoints[nextWaypointIndex + 1].Label == "UseBoat" thennextWaypointIndex += 1-- Call your own customized function to make agent use the boatelseif nextWaypointAction == Enum.PathWaypointAction.Jump thenhumanoid:ChangeState(Enum.HumanoidStateType.Jumping)while humanoid.FloorMaterial ~= Enum.Material.Air dotask.wait(GROUND_WAIT)endhumanoid:Move(nextWaypointPosition - humanoid.RootPart.Position)endelseresetWaypointData()endendlocal function findStartingPoint(waypoints)nextWaypointIndex = 1while nextWaypointIndex + 1 <= #waypoints dolocal dist = waypoints[nextWaypointIndex + 1].Position - humanoid.RootPart.Positiondist = Vector3.new(dist.X, 0, dist.Z)if dist.magnitude >= 2 thenreturnendnextWaypointIndex += 1endendlocal function followPath()-- Compute the pathpathfinderWorking = truewaitForGround()local success, errorMessage = pcall(function()path:ComputeAsync(character.PrimaryPart.Position, DESTINATION)end)if not success or path.Status ~= Enum.PathStatus.Success thenwarn("경로가 계산되지 않았습니다!", errorMessage)returnend-- Get the path waypointswaypoints = path:GetWaypoints()-- Detect if path becomes blockedblockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)-- Check if the obstacle is further down the pathif blockedWaypointIndex >= nextWaypointIndex then-- Stop detecting path blockage until path is re-computedblockedConnection:Disconnect()resetWaypointData()-- Call function to re-compute new pathfollowPath()endend)findStartingPoint(waypoints)moveToNextWaypoint()endfollowPath()경로 계산 및 캐릭터 이동에 대한 내용을 배우기 위해 다음 섹션으로 진행합니다.
경로 생성
경로 탐색은 PathfindingService와 그 CreatePath() 메서드를 통해 시작됩니다 (
| 키 | 설명 | 유형 | 기본값 |
|---|---|---|---|
| AgentRadius | 에이전트 반지름, 스터드 단위. 장애물로부터의 최소 분리를 결정하는 데 유용합니다. | 정수 | 2 |
| AgentHeight | 에이전트 높이, 스터드 단위. 이 값보다 작은 빈 공간, 예를 들어 계단 아래의 공간은 통과할 수 없는 것으로 표시됩니다. | 정수 | 5 |
| AgentCanJump | 경로 탐색 중 점프가 허용되는지 여부를 결정합니다. | 부울 | true |
| AgentCanClimb | 경로 탐색 중 TrussParts를 오를 수 있는지 여부를 결정합니다. 오를 수 있는 경로는 Label이 Climb로 명명되며, 오를 수 있는 경로의 비용은 기본적으로 1입니다. | 부울 | false |
| WaypointSpacing | 경로의 중간 웨이포인트 간의 간격. math.huge로 설정하면 중간 웨이포인트가 없습니다. | 숫자 | 4 |
| Costs | 탐색을 위한 물질 또는 정의된 PathfindingModifiers의 테이블과 그 비용. 에이전트가 특정 물질/지역을 다른 것보다 선호하도록 만드는 데 유용합니다. 자세한 내용은 수정자를 참조하세요. | 테이블 | nil |
경로 계산
CreatePath()로 유효한 경로를 생성한 후, Path:ComputeAsync()를 호출하여 시작점과 목적지에 대한 Vector3를 제공하여 계산해야 합니다 (

Path가 계산되면 시작부터 끝까지의 경로를 추적하는 일련의 웨이포인트를 포함하게 됩니다. 이러한 포인트는 Path:GetWaypoints() 메서드를 사용하여 수집할 수 있습니다 (

경로 이동
각 PathWaypoint는 Position (Vector3)과 Action (PathWaypointAction)으로 구성됩니다. 일반적인 Roblox 캐릭터와 같은 Humanoid를 포함하는 캐릭터를 이동시키는 가장 좋은 방법은 웨이포인트에서 웨이포인트로 Humanoid:Move()를 호출하고 스크립트의 isCurrentWaypointReached() 콜백 (
차단된 경로
많은 Roblox 세계는 동적입니다. 부품이 이동하거나 떨어지거나 바닥이 무너질 수 있습니다. 이는 계산된 경로를 차단하고 캐릭터가 목적지에 도달하지 못하게 할 수 있습니다. 이를 처리하기 위해 Path.Blocked 이벤트에 연결하고 차단된 것을 피하기 위해 경로를 재계산할 수 있습니다 (
경로 탐색 수정자
기본적으로 Path:ComputeAsync()는 시작점과 목적지 사이의 가장 짧은 경로를 반환하지만, 점프를 피하려고 시도합니다. 이는 일부 상황에서 부자연스럽게 보일 수 있습니다. 예를 들어, 경로가 수 swamp 물을 가로지르기보다는 그 주위를 도는 것이 더 논리적일 수 있지만, 물을 가로지르는 경로가 기하학적으로 더 짧기 때문에 그렇게 됩니다.

경로 탐색을 더욱 최적화하려면, 다양한 물질을 가로지르거나 정의된 지역 주위를 돌거나 장애물을 무시하는 경로 탐색 수정자를 구현할 수 있습니다.
물질 비용
Terrain 및 BasePart 물질로 작업할 때, 특정 물질이 다른 물질보다 더 쉽게 통과할 수 있도록 하려면 CreatePath() 내에 Costs 테이블을 포함할 수 있습니다. 모든 물질은 기본적으로 1의 비용을 가지며, 어떤 물질도 그 값을 math.huge로 설정하여 통과할 수 없는 것으로 정의할 수 있습니다.
Costs 테이블의 키는 Enum.Material 이름을 나타내는 문자열 이름이어야 하며, 예를 들어 Enum.Material.Water의 경우 Water, Enum.Material.CrackedLava의 경우 CrackedLava입니다.
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local DESTINATION = Vector3.new(20, 0.5, 20)
local GROUND_WAIT = 0.01
local VELOCITY_MULTIPLIER = 0.0625
local path = PathfindingService:CreatePath({
AgentCanClimb = true,
Costs = {
Water = 20, CrackedLava = 100, Slate = 20
}
})지역 구성
경우에 따라 물질 선호만으로는 충분하지 않을 수 있습니다. 예를 들어, 캐릭터가 특정 지역을 피하도록 하려면, 그 지역 아래의 물질에 관계없이 그렇게 할 수 있습니다. 이는 부품에 PathfindingModifier 객체를 추가하여 달성할 수 있습니다.
지역 주위에 Anchored 부품을 생성하고 CanCollide 속성을 false로 설정합니다.

부품에 PathfindingModifier 인스턴스를 삽입하고, Label 속성을 찾아 DangerZone과 같은 의미 있는 이름을 할당합니다.

CreatePath()의 Costs 테이블 내에 일치하는 DangerZone 키와 관련된 숫자 값을 포함합니다. 수정자는 그 값을 math.huge로 설정하여 통과할 수 없는 것으로 정의할 수 있습니다.
PlayerPathFollow (LocalScript)local PathfindingService = game:GetService("PathfindingService")local Players = game:GetService("Players")local RunService = game:GetService("RunService")local DESTINATION = Vector3.new(20, 0.5, 20)local GROUND_WAIT = 0.01local VELOCITY_MULTIPLIER = 0.0625local path = PathfindingService:CreatePath({AgentCanClimb = true,Costs = {DangerZone = math.huge, Water = 20, CrackedLava = 20, Slate = 20}})
장애물 무시
경우에 따라, 고체 장애물을 통과하는 경로를 찾는 것이 유용할 수 있습니다. 이렇게 하면 특정 물리적 차단기를 통해 경로를 계산할 수 있으며, 계산이 완전히 실패하지 않도록 할 수 있습니다.
객체 주위에 Anchored 부품을 생성하고 CanCollide 속성을 false로 설정합니다.

부품에 PathfindingModifier 인스턴스를 삽입하고 PassThrough 속성을 활성화합니다.

이제 좀비 NPC에서 플레이어 캐릭터로 경로가 계산될 때, 경로는 문을 넘어 확장되며 좀비가 이를 통과하도록 유도할 수 있습니다. 좀비가 문을 열 수 없더라도, 문 뒤에 있는 캐릭터를 "듣는" 것처럼 반응합니다.

경로 탐색 링크
때때로, 일반적으로 통과할 수 없는 공간을 가로지르는 경로를 찾고 다음 웨이포인트에 도달하기 위해 사용자 정의 작업을 수행해야 할 필요가 있습니다. 이는 PathfindingLink 객체를 통해 달성할 수 있습니다.
위의 예를 사용하여 에이전트가 보트를 사용하도록 만들 수 있습니다.

이 예제를 사용하여 PathfindingLink를 생성하려면:
보트의 좌석과 보트의 착륙 지점 근처에 두 개의 Attachments를 생성합니다.

Label 속성에 UseBoat와 같은 의미 있는 이름을 할당합니다. 이 이름은 에이전트가 시작 링크 지점에 도달할 때 사용자 정의 작업을 트리거하는 플래그로 사용됩니다.

CreatePath() 내에 Water 키와 Label 속성 이름과 일치하는 사용자 정의 키를 포함하는 Costs 테이블을 포함합니다. 사용자 정의 키의 값은 Water의 값보다 낮아야 합니다.
PlayerPathFollow (LocalScript)local PathfindingService = game:GetService("PathfindingService")local Players = game:GetService("Players")local RunService = game:GetService("RunService")local DESTINATION = Vector3.new(20, 0.5, 20)local GROUND_WAIT = 0.01local VELOCITY_MULTIPLIER = 0.0625local path = PathfindingService:CreatePath({AgentCanClimb = true,Costs = {UseBoat = 2, Water = 20}})moveToNextWaypoint() 함수 (
LINES 93–114)에서 Label 수정자 이름에 대한 사용자 정의 검사를 사용하여 Humanoid:Move()와는 다른 작업을 수행할 수 있습니다. 이 경우, 에이전트를 보트에 앉히고, 보트를 물 위로 이동시키고, 보트의 착륙 지점에서 에이전트를 내리고, 그 후 에이전트의 경로를 최종 목적지로 계속 진행하도록 할 수 있습니다.
스트리밍 호환성
게임 내 인스턴스 스트리밍은 플레이어의 캐릭터가 세계를 이동할 때 3D 콘텐츠를 동적으로 로드하고 언로드하는 강력한 기능입니다. 그들이 3D 공간을 탐색함에 따라, 새로운 공간의 하위 집합이 그들의 장치로 스트리밍되고 기존의 일부 하위 집합은 스트리밍 아웃될 수 있습니다.
스트리밍이 활성화된 게임에서 PathfindingService를 사용할 때 다음과 같은 모범 사례를 고려하세요:
스트리밍은 캐릭터가 경로를 따라 이동할 때 주어진 경로를 차단하거나 차단 해제할 수 있습니다. 예를 들어, 캐릭터가 숲을 가로질러 달리는 동안, 나무가 그들 앞쪽 어딘가에 스트리밍되어 경로를 차단할 수 있습니다. 경로 탐색이 스트리밍과 원활하게 작동하도록 하려면, 차단된 경로 처리 기술을 사용하고 필요할 때 경로를 재계산하는 것이 좋습니다.
경로 탐색에서 일반적인 접근 방식은 기존 객체의 좌표를 사용하여 계산하는 것입니다. 예를 들어, 경로 목적지를 세계의 기존 TreasureChest 모델의 위치로 설정하는 것입니다. 이 접근 방식은 서버가 항상 세계를 완전히 볼 수 있기 때문에 서버 측 Scripts와 완전히 호환되지만, 클라이언트에서 실행되는 LocalScripts 및 ModuleScripts는 스트리밍되지 않은 객체에 경로를 계산하려고 시도할 경우 실패할 수 있습니다.
이 문제를 해결하기 위해, 지속적인 모델 내의 BasePart 위치로 목적지를 설정하는 것을 고려하세요. 지속적인 모델은 플레이어가 조인한 직후 로드되며 절대 스트리밍 아웃되지 않으므로, 클라이언트 측 스크립트는 PersistentLoaded 이벤트에 연결하고 이벤트가 발생한 후 웨이포인트 생성을 위해 모델에 안전하게 접근할 수 있습니다.
제한 사항 및 실패 요인
경로 탐색 엔진에는 효율적인 처리와 최적의 성능을 보장하기 위한 특정 제한 사항이 포함되어 있습니다. 또한, 경로 탐색 계산은 다양한 이유로 실패할 수 있습니다.

