Okay, creating a robust NPC directly in Verse requires careful handling of AI behaviors, navigation, and interaction with Unreal Engine features like animations (often controlled via Blueprints).
Based on current UEFN Verse capabilities and best practices for AI navigation, here's a script for a slow-walking, melee-only NPC. This script focuses on using the standard navigation system and provides a clear structure for integrating your existing Blueprint animations.
Assumptions:
- You have a Character Blueprint for your NPC. This Blueprint contains the necessary skeletal mesh and has animations (specifically, an Animation Montage for the melee attack and likely idle/walk animations handled by an Animation Blueprint).
- You have baked a Navigation Mesh (NavMesh) in your level so the AI knows where it can walk.
- The NPC Character Blueprint has its
Max Walk Speed property set to a low value to ensure it walks slowly. While potentially adjustable via Verse, setting it in the Blueprint is often the most direct way.
Research Findings Incorporated:
- Navigation: The standard approach in UEFN for AI movement is using the
navigation_interface and the NavigateTo function, which utilizes the level's NavMesh data. This is generally considered the best available technique for obstacle avoidance.
- Character Representation: An NPC is typically represented as an
agent in Verse. Often, this is linked to a character_device or a prop with a fort_character component placed in the level.
- Blueprint Animation Integration: Directly playing specific Animation Montages defined purely in Blueprints from Verse can be complex or limited. A common and robust pattern is to have Verse handle the logic (when to attack) and then signal the Character Blueprint to play the animation. This can be done via Verse-defined interfaces implemented by the Blueprint, or by calling functions exposed from the Blueprint to Verse. This script will use a function call approach, assuming you'll expose a function like
PlayMeleeAttackAnimation from your Character Blueprint to be callable by this Verse device.
- Targeting: Finding players typically involves getting all players in the playspace and determining the closest one within range.
- Melee Damage: Applying damage is done using the
Damageable interface, typically found on player characters (fort_character).
using { /Fortnite.com/Characters }
using { /Fortnite.com/Devices }
using { /Fortnite.com/AI }
using { /Fortnite.com/Playspaces }
using { /Verse.org/Simulation }
using { /UnrealEngine.com/Temporary/SpatialMath }
using { /UnrealEngine.com/Temporary/Navigation }
using { /UnrealEngine.com/Temporary/Animation } # May be needed for specific animation calls, depending on setup
# Define an interface that the NPC Blueprint should implement (or have a matching function exposed)
# This allows Verse to tell the Blueprint when to play the attack animation.
melee_npc_anim_interface := interface:
# Call this from Verse to trigger the Melee Attack Animation Montage in the NPC's Animation Blueprint
PlayMeleeAttackAnimation():void
melee_npc_controller := class(creative_device):
#-- EDITABLE PROPERTIES --#
# Link this to the Character Device or Prop representing your NPC in the editor.
@editable
NPCCharacter : creative_prop = creative_prop{}
# How far the NPC can 'see' or detect players.
@editable
DetectionRadius : float = 1500.0 # Example: 15 meters
# The range within which the NPC will initiate a melee attack.
@editable
MeleeAttackRadius : float = 150.0 # Example: 1.5 meters
# Time in seconds between consecutive melee attacks.
@editable
AttackCooldown : float = 2.0
# Damage dealt by each melee attack.
@editable
AttackDamage : float = 10.0
# Optional: If direct animation control from Verse is feasible and preferred.
# Link this to the Skeletal Mesh Component of your NPC Character Blueprint if needed.
# @editable
# NPCSkeletalMesh : skeletal_mesh_component = skeletal_mesh_component{}
#-- INTERNAL STATE --#
var MaybeNavigationTarget : ?agent = false
var IsAttackOnCooldown : logic = false
# Main function called when the game starts
OnBegin<override>()<suspends>:void=
# Get the Agent representation of our NPC Character
if (FortCharacter := NPCCharacter.GetFortCharacter[]):
NPCBrainLoop(FortCharacter) # Start the main AI loop
else:
Print("Error: Failed to get FortCharacter for the NPC.")
# The main AI Brain Loop for the NPC
NPCBrainLoop(NPC_Agent : agent)<suspends> : void =
loop:
# Find the nearest player to target
set MaybeNavigationTarget = FindNearestPlayer(NPC_Agent)
if (TargetAgent := MaybeNavigationTarget?):
# We have a target
TargetLocation := TargetAgent.GetTransform().Translation
NPCLocation := NPC_Agent.GetTransform().Translation
DistanceToTarget := Distance(NPCLocation, TargetLocation)
if (DistanceToTarget <= MeleeAttackRadius):
# Target is in melee range - ATTACK
# First, ensure any ongoing navigation is stopped
if (Navigatable := NPC_Agent.GetNavigatable[]):
Navigatable.CancelNavigation()
PerformMeleeAttack(NPC_Agent, TargetAgent)
else if (DistanceToTarget <= DetectionRadius):
# Target is in detection range, but not melee range - CHASE
NavigateToTarget(NPC_Agent, TargetAgent)
else:
# Target is out of detection range, lose target
set MaybeNavigationTarget = false
# Optional: Implement idle behavior here (e.g., wander, return to spawn)
if (Navigatable := NPC_Agent.GetNavigatable[]):
Navigatable.CancelNavigation() # Stop moving if target is lost
Sleep(0.5) # Short delay before checking for targets again
else:
# No target found
# Optional: Implement idle behavior here
Sleep(1.0) # Wait a bit before scanning for players again
# Ensure a small delay each loop iteration to prevent performance issues
Sleep(0.1)
# Finds the nearest player within the DetectionRadius
FindNearestPlayer(NPC_Agent : agent) : ?agent =
NPCLocation := NPC_Agent.GetTransform().Translation
var ClosestPlayer : ?agent = false
var MinDistanceSquared : float = DetectionRadius * DetectionRadius
# Get all players in the current playspace
AllPlayers := GetPlayspace().GetPlayers()
for (Player : player, PlayerCharacter : agent := AllPlayers):
PlayerLocation := PlayerCharacter.GetTransform().Translation
DistanceSquared := DistanceSquared(NPCLocation, PlayerLocation)
if (DistanceSquared <= MinDistanceSquared):
set MinDistanceSquared = DistanceSquared
set ClosestPlayer = option{PlayerCharacter}
return ClosestPlayer
# Handles moving the NPC towards the target using the navigation system
NavigateToTarget(NPC_Agent : agent, TargetAgent : agent)<suspends> : void =
if (Navigatable := NPC_Agent.GetNavigatable[]):
# Navigate towards the target agent's current location
NavigateResult := Navigatable.NavigateTo(TargetAgent.GetTransform().Translation)
# Handle Navigation Result (Optional but recommended for robustness)
# You could add logic here to check if NavigateResult indicates Failure or Invalid Path
# and decide what to do (e.g., wait, try finding a new path, pick new target)
# For simplicity, this example doesn't explicitly handle failure states after initiating navigation.
# The loop will re-evaluate distance and re-issue NavigateTo on subsequent ticks if needed.
Sleep(0.1) # Short delay to allow navigation to progress before next check
else:
Print("Warning: NPC Agent does not have a Navigatable component.")
Sleep(1.0) # Wait if navigation isn't possible
# Performs the melee attack logic
PerformMeleeAttack(NPC_Agent : agent, TargetAgent : agent)<suspends> : void =
# Check if attack is already on cooldown
if (not IsAttackOnCooldown?):
# Set cooldown flag
set IsAttackOnCooldown = true
Print("NPC attacking Target!")
# --- Trigger the Animation ---
# This is the crucial part for integrating Blueprint animations.
# Assumes your NPC Character Blueprint has a function `PlayMeleeAttackAnimation`
# exposed to Verse or implements the `melee_npc_anim_interface`.
# You MUST implement this part in your NPC's Blueprint.
if (AnimInterface := NPC_Agent.FindComponentByClass[melee_npc_anim_interface]()):
AnimInterface.PlayMeleeAttackAnimation()
# OR, if calling a directly exposed function (less standard but possible):
# NPC_Agent.PlayMeleeAttackAnimation() # Replace with actual function name if exposed differently
# --- Apply Damage ---
# Ensure the target is damageable
if (DamageableTarget := TargetAgent.GetFortCharacter[].GetDamageable[]):
# Deal damage (Source is the NPC agent itself)
DamageResult := DamageableTarget.Damage(AttackDamage, NPC_Agent)
# You could check DamageResult if needed
# Wait for the cooldown duration before allowing another attack
Sleep(AttackCooldown)
set IsAttackOnCooldown = false
else:
# Attack is on cooldown, do nothing this frame except wait for next opportunity
Sleep(0.1)
Explanation and How to Use:
- Create the Verse Device: Create a new Verse device in UEFN and paste this code into it. Build the Verse code (
Ctrl+Shift+B).
- Place in Level: Drag the compiled Verse device into your level.
- Configure Properties:
- Select the Verse device in the Outliner.
- In the Details panel, link the
NPCCharacter property to the creative_prop or character_device in your level that represents your NPC.
- Adjust
DetectionRadius, MeleeAttackRadius, AttackCooldown, and AttackDamage as needed for gameplay balance.
- Blueprint Setup (CRUCIAL):
- Open your NPC's Character Blueprint.
- Expose Animation Function: You need a way for Verse to tell this Blueprint to play the attack animation montage. The recommended way is using a Verse Interface:
- In your Verse file, define the
melee_npc_anim_interface (as shown in the code).
- In your Character Blueprint, go to Class Settings -> Interfaces -> Add -> Search for
melee_npc_anim_interface and add it.
- In the My Blueprint panel under Interfaces, you'll see
PlayMeleeAttackAnimation. Double-click it.
- In the event graph that opens, add the nodes to play your specific Melee Attack Animation Montage (e.g., using a
Play Montage node, targeting the character's Mesh). Compile and save the Blueprint.
- Set Walk Speed: Ensure the
CharacterMovement component in your Blueprint has its Max Walk Speed set to a low value (e.g., 100-200) for the slow walk effect.
- Animation Blueprint: Make sure your Animation Blueprint handles transitions between Idle, Walking (based on speed), and connects to the Melee Attack Montage when triggered.
- NavMesh: Ensure you have a
Nav Mesh Bounds Volume covering the playable area and have built the navigation (Build -> Build Paths in the main editor toolbar).
- Test: Launch a session and test the NPC's behavior.
How it achieves "Fun to Fight Against":
- Slow Speed: Makes the NPC less overwhelming and easier to kite or dodge.
- Clear Behavior: Follows a simple Chase -> Attack logic.
- Telegraphed Attack: The melee animation itself should telegraph the attack (this depends on the animation you use). The
AttackCooldown prevents spamming.
- Reliable Navigation: Uses the standard
navigation_interface, which handles pathfinding and basic obstacle avoidance around static geometry defined in the NavMesh. Dynamic obstacles might still pose a challenge depending on the complexity.
- Tunable Parameters: You can easily adjust radii, damage, and cooldown to balance the difficulty.
This script provides a solid foundation using current UEFN Verse best practices for NPC AI navigation and integrates with Blueprints for animation control, avoiding speculation on direct Verse animation features that might be limited or change.