Creating a Melee NPC in UEFN
Creating a fun-to-fight melee NPC in UEFN requires careful implementation of navigation, combat mechanics, and animation integration. The following Verse script creates a slow-moving melee NPC that can navigate around obstacles and engage players in close combat.
The Complete Script
using { /Fortnite.com/AI }
using { /Fortnite.com/Characters }
using { /Fortnite.com/Devices }
using { /Verse.org/Simulation }
using { /UnrealEngine.com/Temporary/Diagnostics }
using { /UnrealEngine.com/Temporary/SpatialMath }
using { /Verse.org/Random }
using { /Verse.org/Assets }
# A Verse-authored NPC Behavior for a slow-moving melee attacker
melee_npc_behavior<public> := class(npc_behavior):
# How much damage the NPC deals with each attack
@editable
MeleeDamage<public>:float = 15.0
# How close the NPC needs to be to attack
@editable
AttackRange<public>:float = 150.0
# How far the NPC can detect players
@editable
DetectionRange<public>:float = 2000.0
# How long to wait between attacks
@editable
AttackCooldown<public>:float = 2.0
# The attack animation to play
@editable
MeleeAttackAnimation<public>:animation_sequence = animation_sequence{}
# This function runs when the NPC is spawned in the world
OnBegin<override>()<suspends>:void =
if:
# Get the Agent (the NPC)
Agent := GetAgent[]
# Get the Fortnite Character interface
Character := Agent.GetFortCharacter[]
# Get the Navigatable Interface, allows us to tell the NPC to move
Navigatable := Character.GetNavigatable[]
# Get the Focus Interface, allows us to control where the NPC is looking
Focus := Character.GetFocusInterface[]
# Get the Animation Controller, allows us to play animations
AnimController := Character.GetAnimationController[]
then:
# Store the spawn location
NPCSpawnPoint := Character.GetTransform().Translation
# Main behavior loop - continues as long as the NPC is alive
loop:
if (not Character.IsActive[]):
break
# Find the nearest player to target
Target := FindNearestTarget(Character, DetectionRange)
if (Target = none):
# No target found, wait a moment before checking again
Sleep(1.0)
else:
# Target found, pursue and attack
PursueAndAttackTarget(Character, Target, Navigatable, Focus, AnimController)
# Brief pause before next iteration
Sleep(0.5)
# Finds the nearest player within detection range
FindNearestTarget<private>(Character:fort_character, Range:float)<transacts><decides>:fort_character =
var ClosestTarget:?fort_character = none
var ClosestDistance:float = Range
# Get all players in the game
AllPlayers := GetPlayspace().GetPlayers()
# Check each player to find the closest one
for (Player : AllPlayers):
PlayerCharacter := Player.GetFortCharacter[]
if (PlayerCharacter.IsActive[]):
NPCPosition := Character.GetTransform().Translation
PlayerPosition := PlayerCharacter.GetTransform().Translation
Distance := Distance(NPCPosition, PlayerPosition)
if (Distance < ClosestDistance):
ClosestDistance = Distance
ClosestTarget = option{PlayerCharacter}
# Return the closest target if one was found
if (Target := ClosestTarget?):
return Target
# Pursues and attacks the target
PursueAndAttackTarget<private>(Character:fort_character, Target:fort_character,
Navigatable:navigatable, Focus:focus_interface,
AnimController:animation_controller)<suspends>:void =
var LastAttackTime:float = 0.0
var CurrentTime:float = 0.0
# Continue pursuing and attacking until the target is gone or NPC dies
loop:
if (not Character.IsActive[] or not Target.IsActive[]):
break
# Get positions
NPCPosition := Character.GetTransform().Translation
TargetPosition := Target.GetTransform().Translation
# Calculate distance to target
DistanceToTarget := Distance(NPCPosition, TargetPosition)
# Update current time
CurrentTime += 0.5
if (DistanceToTarget <= AttackRange):
# In attack range - attack if cooldown has passed
if (CurrentTime - LastAttackTime >= AttackCooldown):
# Focus on target
spawn { Focus.MaintainFocus(Target) }
# Play attack animation
AnimController.PlayAnimation(MeleeAttackAnimation)
# Wait for animation to reach the point of impact (approximately halfway)
Sleep(0.5)
# Check if still in range after animation delay
NewNPCPosition := Character.GetTransform().Translation
NewTargetPosition := Target.GetTransform().Translation
NewDistance := Distance(NewNPCPosition, NewTargetPosition)
if (NewDistance <= AttackRange):
# Deal damage to the target
Target.Damage(MeleeDamage)
# Update last attack time
LastAttackTime = CurrentTime
# Wait for the rest of the animation
Sleep(0.5)
else:
# Still on cooldown, wait a moment
Sleep(0.5)
else:
# Not in attack range - navigate toward target
# Create a navigation target from the player
NavTarget := MakeNavigationTarget(Target)
# Set movement type to walking (slow)
MovementType := movement_type.Walking
# Navigate to the target
Navigatable.NavigateTo(NavTarget, MovementType, AttackRange)
# Focus on the target while moving
spawn { Focus.MaintainFocus(Target) }
# Wait a moment before checking position again
Sleep(1.0)
Key Features Explained
Navigation System
The NPC uses the navigatable interface to move around the environment, which provides built-in obstacle avoidance. The NavigateTo function handles pathfinding automatically, allowing the NPC to navigate around obstacles in the environment[1][7].
Navigatable.NavigateTo(NavTarget, MovementType, AttackRange)
The MakeNavigationTarget function creates a navigation target from the player character, which the NPC will follow[1]. The AttackRange parameter in NavigateTo defines how close the NPC needs to get to consider its navigation complete[1].
Combat Mechanics
The NPC uses a melee attack system with the following components:
- Detection Range: The NPC can detect players within a configurable range (default 2000 units)[5][7].
- Attack Range: The NPC will attack when within a certain distance (default 150 units)[1][5].
- Attack Cooldown: A delay between attacks to prevent spam (default 2 seconds)[1].
- Damage Amount: Configurable damage per attack (default 15)[5].
When in attack range, the NPC will:
- Focus on the target using the
focus_interface[1].
- Play the attack animation[1][8].
- Wait for the animation to reach the point of impact.
- Check if still in range and deal damage if so.
Animation Integration
The script uses the character's animation_controller to play animations[1][4]. The attack animation is referenced as an animation_sequence that can be set in the editor[8].
AnimController.PlayAnimation(MeleeAttackAnimation)
This allows for seamless integration with animations defined in blueprints[6][8].
Movement Speed Control
The NPC is configured to move slowly by using the Walking movement type[1][7]:
MovementType := movement_type.Walking
This creates a more approachable enemy that players have time to react to, making the combat more strategic and fun[6].
Implementation Notes
-
Editable Properties: All key parameters are marked with @editable to allow designers to tune the NPC behavior without changing code[1][7].
-
Target Selection: The NPC finds the nearest player within detection range using the FindNearestTarget function[5][7].
-
Main Loop Structure: The behavior uses a main loop that continues as long as the NPC is alive, alternating between searching for targets and pursuing/attacking them[1][7].
-
Error Handling: The script includes proper null checks and condition verification to prevent runtime errors[1][7].
To use this script, create a new NPC Behavior in UEFN, paste this code, and assign it to an NPC Character Definition with the Type set to either Guard or Custom[7][10]. Then place an NPC Spawner in your level and set the Character Definition to your newly created definition[7][10].
Remember to set the MeleeAttackAnimation property to your attack animation asset from your blueprint[8].