Keep Your Guards on a Leash (Literally)
Tutorial beginner

Keep Your Guards on a Leash (Literally)

Updated beginner

Keep Your Guards on a Leash (Literally)

Ever spent hours building the perfect stronghold, only to have your elite guard patrol right into the storm because they have the spatial awareness of a drunk chicken? It’s frustrating. You don’t need to be a coding wizard to fix this; you just need to understand how to tie your NPCs down.

In this tutorial, we’re going to build a Leash Volume. Think of it as an invisible forcefield around your guard’s spawn point. No matter how much they want to wander off to loot the island, they’ll be snapped back into their designated zone. We’ll use Verse to connect this leash to your guard spawners, ensuring your defenses actually stay where you put them.

What You'll Learn

  • The Scene Graph: How devices talk to each other in UEFN.
  • Arrays: Grouping multiple devices together (like a squad).
  • Events: Triggering actions when specific things happen (like spawning).
  • Leash Logic: How to define the "inner" and "outer" boundaries of your guard’s territory.

How It Works

In Fortnite Creative, you probably know the Guard Spawner device. It spawns guards. You also know AI Patrol Paths. They tell guards where to walk. But neither of those stops a guard from accidentally walking off a cliff or into the next player’s base.

Enter the Leash.

Imagine your guard is a dog. The leash has two measurements:

  1. Inner Radius: The "home base." The guard must spend most of their time here. It’s their living room.
  2. Outer Radius: The "backyard." The guard can wander out here to chase squirrels (players), but they can’t go past this line. If they try, the leash pulls them back.

In Verse, we create a custom device that holds these two numbers. Then, we tell the device: "When a guard spawns from these spawners, apply this leash to them."

The Scene Graph Connection

UEFN is built on a Scene Graph. Think of this as the family tree of your island. Every device, prop, and player is a node in this tree. When we write Verse, we aren't just writing code in a vacuum; we are reaching out from our custom device node and grabbing hold of other nodes (like the Guard Spawner) to listen for their "events" (like SpawnedEvent).

The "Array" Concept

You might have ten guard spawners in your stronghold. You don’t want to write ten separate lines of code. In programming, an Array is just a list. We’ll create a list called GuardsSpawners. In the editor, you can drag and drop all ten spawners into this list. Our code will then loop through the list and apply the leash to each one automatically.

Let's Build It

We are going to create a device that acts as the leash controller.

Step 1: The Setup

  1. Open UEFN and go to the Verse tab.
  2. Create a new Verse file (e.g., GuardLeash.verse).
  3. Place a Guard Spawner device in your map. Let’s call it "Main Guard Spawner."
  4. We will write the code to control it.

Step 2: The Code

Here is the complete Verse code for our Leash Device. Copy this into your .verse file.

# GuardLeash.verse
# This device defines a leash volume for guards.

using { /Fortnite.com/Devices }
using { /Fortnite.com/Characters }
using { /Verse.org/Simulation }
using { /UnrealEngine.com/Temporary/SpatialMath }
using { /Verse.org/SpatialMath }

# We create a new class called 'LeashDevice'.
# Think of this as a new type of device you can place in the editor.
LeashDevice := class(creative_device):
    # @editable means this variable shows up in the editor sidebar.
    # You can change it without touching code.
    
    # 1. The Inner Radius (Home Base)
    # Guards should stay inside this distance from the spawn center.
    @editable
    InnerRadius:float = 500.0
    
    # 2. The Outer Radius (The Leash Limit)
    # Guards cannot go further than this distance.
    @editable
    OuterRadius:float = 1000.0
    
    # 3. The List of Spawners
    # This is an 'Array'. It's a list where you drag in your Guard Spawner devices.
    # We leave it empty for now; you'll fill it in the editor.
    @editable
    ConnectedSpawners:[]npc_spawner_device = array{}
    
    # This function runs when the game starts (or when the island loads).
    OnBegin<override>()<suspends>:void=
        # We loop through every device in our ConnectedSpawners list.
        for (Spawner : ConnectedSpawners):
            # We subscribe to its 'SpawnedEvent'.
            # This means: "Hey Spawner, tell me every time you spawn a guard."
            Spawner.SpawnedEvent.Subscribe(OnGuardSpawned)

    # This function runs whenever a guard is spawned.
    OnGuardSpawned(SpawnedGuard:agent):void=
        # Get the position of the guard.
        # We cast agent to fort_character to access position info.
        if (GuardChar := fort_character[SpawnedGuard]):
            GuardPosition := GuardChar.GetTransform().Translation
            
            # Get the position of the leash device itself (our anchor point).
            LeashPosition := GetTransform().Translation
            
            # Calculate the distance between the guard and the leash device.
            Diff := GuardPosition - LeashPosition
            GuardDist := Diff.Length()
            
            # If the guard is outside the Outer Radius, we snap them back.
            # This simulates the "leash" pulling them in.
            if (GuardDist > OuterRadius):
                # Calculate a direction vector from the guard to the leash center.
                Direction := Normal(LeashPosition - GuardPosition)
                
                # Move the guard to the edge of the Outer Radius.
                NewPosition := LeashPosition + (Direction * OuterRadius)
                GuardChar.TeleportTo[NewPosition, GuardChar.GetTransform().Rotation]
                
                # Optional: Print a message to the chat so you know it worked.
                Print("Guard snapped back to leash!")```

### Walkthrough: What Just Happened?

1.  **`class(creative_device)`**: We defined a new device type. This is your "Leash Controller."
2.  **`@editable` Variables**: `InnerRadius` and `OuterRadius` are now sliders in the editor. You can tweak them to 500 and 1000 without rewriting code.
3.  **`ConnectedSpawners:[]creative_device`**: This is our **Array**. In the editor, you will see a slot for this. You drag your Guard Spawner into it.
4.  **`OnBegin`**: This is the setup phase. It loops through your list of spawners.
5.  **`Subscribe(OnGuardSpawned)`**: This is the magic. Instead of constantly checking "Is the guard here? Is the guard here?" (which is bad for performance), we tell the Spawner: "Call me when you spawn something." This is an **Event**.
6.  **`OnGuardSpawned`**: When the event fires, we grab the new guard, check their distance, and if theyre too far, we teleport them back to the edge of the leash.

## Try It Yourself

**Challenge:** The current code snaps the guard back *only* when they spawn. But what if a guard walks away from the spawn point over time?

**Hint:** Look at the `OnBegin` function. Instead of just subscribing to `SpawnedEvent`, can you subscribe to the guard's own `MovedEvent`? Or, simpler for a beginner: Add a loop inside `OnGuardSpawned` that waits (`<suspends>`) for a few seconds, checks the distance again, and snaps them back if they wandered off?

**Goal:** Make a guard that spawns at the center, wanders out to the outer radius, but gets "yanked" back if they go too far.

## Recap

You just built a dynamic leash system using Verse. You learned how to:
*   Create a custom device class.
*   Use `@editable` variables to make settings user-friendly.
*   Use Arrays (`[]`) to manage multiple devices.
*   Subscribe to Events (`SpawnedEvent`) to react to gameplay moments.

Your guards are now tethered to their post. No more accidental cliff dives. Now go build a stronghold that actually holds.

## References

*   https://dev.epicgames.com/documentation/en-us/uefn/stronghold-04-set-up-leash-devices-in-unreal-editor-for-fortnite
*   https://dev.epicgames.com/documentation/en-us/fortnite/stronghold-04-set-up-leash-devices-in-unreal-editor-for-fortnite
*   https://dev.epicgames.com/documentation/en-us/uefn/verse-stronghold-template-2-add-leashes-in-unreal-editor-for-fortnite
*   https://dev.epicgames.com/documentation/en-us/fortnite/create-custom-npc-behavior-in-unreal-editor-for-fortnite
*   https://dev.epicgames.com/documentation/en-us/uefn/create-custom-npc-behavior-in-unreal-editor-for-fortnite

Verse source files

Turn this into a guided course

Add Defines a leash volume that can be assigned to guards to your free study plan — we'll suggest related pages and stitch the lot into one compile-checked, self-guided lesson with worked examples and quizzes.

Original tutorial generated by Verse Island from the Verse/UEFN knowledge base, with references to the Epic Games sources above. Code is validated against the knowledge base.

Comments

    Sign in to vote, comment, or suggest an edit. Sign in