Raycastでプレイヤーを見つけて追うNPC

敵NPCがプレイヤーを見つけると追いかけ、壁に隠れると探索に切り替わる仕組みを作ります。Workspace:Raycast() で視界を調べ、PathfindingService で歩ける経路を求めます。

状態 NPCの動き
探索 探索ポイントを順番に巡回します。見失った直後は、最後にプレイヤーを見た場所へ先に向かいます。
追跡 見えているプレイヤーのうち最も近い相手に向かいます。相手が移動するので、経路を定期的に計算し直します。

Roblox Studioで準備する

  1. 平らな床の上にR6またはR15のリグを挿入します。NPCのモデルには Head、Humanoid、HumanoidRootPart が必要です。リグのパーツの Anchored をオフにします。
  2. NPCとプレイヤーの間に置ける壁を作ります。壁を固定し、CanCollide と CanQuery をオンにします。壁の横には通れる幅を残します。
  3. Workspace に SearchPoints という Folder を作り、その中に 01、02 という名前の Part を置きます。NPCが歩いて行ける床の上に置き、Anchored をオン、CanCollide と CanQuery をオフにします。配置が済んだら Transparency を 1 にして隠せます。
  4. NPCモデルの直下にサーバー側の Script を追加し、次のコードを貼り付けます。

NPCのスクリプト

local Players = game:GetService("Players")
local PathfindingService = game:GetService("PathfindingService")
local Workspace = game:GetService("Workspace")

local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local root = npc:WaitForChild("HumanoidRootPart")
local head = npc:WaitForChild("Head")

local SIGHT_RANGE = 60
local HALF_FOV = math.rad(60)
local CHECK_INTERVAL = 0.15
local REPATH_INTERVAL = 0.9
local SEARCH_TIMEOUT = 7
local ARRIVAL_DISTANCE = 2

local searchPoints = {}
for _, point in Workspace:WaitForChild("SearchPoints"):GetChildren() do
    if point:IsA("BasePart") then
        table.insert(searchPoints, point)
    end
end
assert(#searchPoints >= 2, "Workspace.SearchPoints に Part を2つ以上置いてください")
table.sort(searchPoints, function(a, b)
    return a.Name < b.Name
end)

local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Exclude
rayParams.FilterDescendantsInstances = { npc }

local function findVisiblePlayer()
    local closestRoot = nil
    local closestDistance = math.huge

    for _, player in Players:GetPlayers() do
        local character = player.Character
        local targetHumanoid = character and character:FindFirstChildOfClass("Humanoid")
        local targetRoot = character and character:FindFirstChild("HumanoidRootPart")
        if not targetHumanoid or targetHumanoid.Health <= 0 or not targetRoot then
            continue
        end

        local direction = targetRoot.Position - head.Position
        local distance = direction.Magnitude
        if distance == 0 or distance > SIGHT_RANGE or distance >= closestDistance then
            continue
        end
        if root.CFrame.LookVector:Dot(direction.Unit) < math.cos(HALF_FOV) then
            continue
        end

        local hit = Workspace:Raycast(head.Position, direction, rayParams)
        if hit and hit.Instance:IsDescendantOf(character) then
            closestRoot = targetRoot
            closestDistance = distance
        end
    end

    return closestRoot
end

local function findWaypoints(destination)
    local path = PathfindingService:CreatePath({ AgentCanJump = true })
    local ok = pcall(function()
        path:ComputeAsync(root.Position, destination)
    end)
    local waypoints = {}
    if ok and path.Status == Enum.PathStatus.Success then
        waypoints = path:GetWaypoints()
    end
    path:Destroy()
    return waypoints
end

local function isNear(position)
    local offset = position - root.Position
    return Vector3.new(offset.X, 0, offset.Z).Magnitude <= ARRIVAL_DISTANCE
end

local pointIndex = 1
local lastSeenPosition = nil
local searchDeadline = 0
local previousTarget = nil
local previousPoint = nil
local nextRepath = 0
local waypoints = {}
local waypointIndex = 2
local movingTo = nil

while humanoid.Health > 0 do
    local now = os.clock()
    local target = findVisiblePlayer()

    if target then
        lastSeenPosition = target.Position
        searchDeadline = now + SEARCH_TIMEOUT
    elseif lastSeenPosition and (isNear(lastSeenPosition) or now >= searchDeadline) then
        lastSeenPosition = nil
    end

    local searchPoint = nil
    local destination = lastSeenPosition
    if not destination then
        if isNear(searchPoints[pointIndex].Position) then
            pointIndex = pointIndex % #searchPoints + 1
        end
        searchPoint = searchPoints[pointIndex]
        destination = searchPoint.Position
    end

    npc:SetAttribute("AIState", if target then "Chase" else "Search")

    if target ~= previousTarget or searchPoint ~= previousPoint or now >= nextRepath then
        if target ~= previousTarget or searchPoint ~= previousPoint then
            humanoid:MoveTo(root.Position)
        end
        waypoints = if isNear(destination) then {} else findWaypoints(destination)
        waypointIndex = 2 -- 最初の経由点は経路の出発地点
        movingTo = nil
        nextRepath = os.clock() + REPATH_INTERVAL
        previousTarget = target
        previousPoint = searchPoint
    end

    local waypoint = waypoints[waypointIndex]
    while waypoint and isNear(waypoint.Position) do
        waypointIndex += 1
        waypoint = waypoints[waypointIndex]
    end

    if waypoint and waypoint ~= movingTo then
        if waypoint.Action == Enum.PathWaypointAction.Jump then
            humanoid.Jump = true
        end
        humanoid:MoveTo(waypoint.Position)
        movingTo = waypoint
    elseif not waypoint then
        humanoid:MoveTo(root.Position)
    end

    task.wait(CHECK_INTERVAL)
end

Raycastと経路探索の仕組み

  • 距離と視野角を調べる。 NPCの頭からプレイヤーの胴体までが SIGHT_RANGE の範囲内で、NPCの前方との角度が HALF_FOV 以下ならRaycastを実行します。ここでは左右それぞれおよそ60度です。
  • 最初に当たったものを調べる。 第2引数の targetRoot.Position - head.Position は、向きと長さを持つベクトルです。レイはプレイヤーまで伸び、途中に判定対象の壁があれば先に壁に当たります。NPC自身は RaycastParams で除外し、最初の命中先がプレイヤーのモデルに属するときに発見とします。
  • 見えている間だけ位置を記録する。 壁に隠れると AIState は Search に変わります。最後に見た位置に着くか、最後に見てから7秒経つと SearchPoints の巡回に移ります。探索中に再発見すると Chase に戻ります。
  • 経由点を歩きながら視界を調べる。 CreatePath() と ComputeAsync() で求めた経由点へ Humanoid:MoveTo() で進みます。到着イベントを待たずに視界を調べるため、移動中にも壁に隠れたプレイヤーを見失えます。経路が作れないときは、その場で次の計算を待ちます。

プレイテスト

  1. Studioの プレイ で始めます。エクスプローラーでNPCモデルを選択し、プロパティの属性 AIState を確認します。
  2. NPCの正面、60スタッド以内に立ちます。間に壁がなければ Chase になり、NPCが近づきます。
  3. 壁の裏へ移動します。Search に変わり、NPCは最後に見た位置を調べてから探索ポイントを巡回します。NPCが壁を回り込んで再び視界に捉えると、その場で追跡に戻ります。
  4. 壁から出てNPCの正面に入ります。Chase に戻ることを確認します。

壁越しに見つかる場合は、壁の CanQuery と、NPCの頭からプレイヤーの胴体までを壁が遮っているかを確認します。NPCが歩けない場合は壁の横を広げ、Studioのビューポートでナビゲーションメッシュを表示して歩ける場所を確認できます。この例の到着判定は床と平行な距離を使うため、探索ポイントは同じ階に置いてください。

関連ページ