Skip to content
The Chat Archive
gemini-2.0-flash-grounding· Google LMArena Search Arena 24K

Write a well commented and bug free Verse script that controls an npc and makes them…

  1. User

    Write a well commented and bug free Verse script that controls an npc and makes them very fun to fight against. Include instructions when finished.

  2. Assistant

    Okay, I can help you create a Verse script for a fun and challenging NPC to fight. This script will focus on making the NPC's behavior engaging and less predictable. I'll include comments to explain each part, and after the script, I'll give you instructions on how to use it in Fortnite Creative.

    using { /Fortnite.com/Devices }
    using { /Fortnite.com/AI }
    using { /Fortnite.com/Characters }
    using { /Fortnite.com/Creative }
    using { /Fortnite.com/Simulation }
    using { /Fortnite.com/Teams }
    using { /Fortnite.com/Environment }
    using { /UnrealEngine.com/Temporary/Diagnostics }
    
    # A Verse device that makes an NPC fun to fight.
    npc_controller := module:
        # --------------------------------------------------
        # Editable Properties (Set these in the editor)
        # --------------------------------------------------
    
        @editable
        AIManager : ai_spawner = AIManager {} # Reference to your AI Spawner device
    
        @editable
        AggroRange : float = 2000.0 # How close the player needs to be to trigger the NPC
    
        @editable
        RetreatRange : float = 500.0 # How far the NPC will try to stay from the player
    
        @editable
        StrafeSpeed : float = 200.0 # Speed of strafing movement
    
        @editable
        MaxHealth : int = 100 # Maximum health of the NPC
    
        @editable
        DamageAmount : int = 10  # How much damage the NPC deals
    
        @editable
        Accuracy : float = 0.8  # NPC's aiming accuracy (0.0 to 1.0)
    
        @editable
        FireRate : float = 1.0 # Shots per second
    
        # --------------------------------------------------
        # Internal State
        # --------------------------------------------------
    
        var Agent : agent = Agent{} # The agent controlled by this script
        var Health : int = MaxHealth # Current health of the NPC
        var IsAggroed : logic = false # Whether the NPC is currently engaged with the player
        var LastAttackTime : float = 0.0 # Tracks when the NPC last attacked
    
        OnBegin<override>() : void =
            # Find the NPC agent spawned by the AI spawner.  This assumes only one NPC is spawned!
            Sleep(0.1) # Wait briefly for the AI spawner to initialize.
            if(AIAgent := AIManager.GetAgents()[0]):
                Agent := AIAgent
                Print("NPC Controller: Agent found.")
                # Subscribe to damage events (if we can get the character)
                if (AISpawnable := AIManager.GetAISpawnable()):
                    AISpawnable.DamageEvent.Subscribe(HandleDamage)
                else:
                    Print("NPC Controller: Failed to get AISpawnable for damage subscription.")
            else:
                Print("NPC Controller: No agent found from AI spawner!")
    
            # Main loop to control the NPC's behavior
            loop:
                MainLoopCycle()
                Sleep(0.05) # Short delay to prevent excessive CPU usage
    
        # --------------------------------------------------
        # Main Loop
        # --------------------------------------------------
        MainLoopCycle() : void =
            if (Agent.IsValid()):
                # Find the closest player
                if (Player := FindNearestPlayer()):
                    DistanceToPlayer := Distance(Agent.GetTransform().Translation, Player.GetTransform().Translation)
    
                    # Aggro/De-aggro Logic
                    if (not IsAggroed and DistanceToPlayer &lt;= AggroRange):
                        IsAggroed = true
                        Print("NPC Controller: Aggroed!")
                    else if (IsAggroed and DistanceToPlayer &gt; AggroRange * 1.5): #Added some leniency to the de-aggro range
                        IsAggroed = false
                        Print("NPC Controller: De-aggroed.")
    
                    # Behavior based on aggro state
                    if (IsAggroed):
                        EngagePlayer(Player, DistanceToPlayer)
                    else:
                        # Optionally, add wandering behavior here if desired
                        # For now, just stand still
                        StopMoving()
                else:
                    StopMoving() # No player found, stop moving
            else:
                Print("NPC Controller: Agent is invalid.  Waiting...")
                Sleep(1.0) # Wait and try again
    
        # --------------------------------------------------
        # Player Engagement Logic
        # --------------------------------------------------
        EngagePlayer(Player : agent, DistanceToPlayer : float) : void =
            # Retreat if too close
            if (DistanceToPlayer &lt;= RetreatRange):
                RetreatFromPlayer(Player)
            else:
                # Strafe and Attack
                StrafeAroundPlayer(Player)
                MaybeAttackPlayer(Player)
    
    
        # --------------------------------------------------
        # Movement Functions
        # --------------------------------------------------
        StrafeAroundPlayer(Player : agent) : void =
            # Calculate a strafe direction (perpendicular to the player's direction)
            PlayerDirection := GetDirectionToPlayer(Player)
            StrafeDirection := Vector3{X := -PlayerDirection.Y, Y := PlayerDirection.X, Z := 0.0}.GetNormalized() #90 degree rotation
    
            # Apply strafing, alternating directions for variety
            if (Simulation.RandomFloat() &lt; 0.5):
                MoveTo(Agent, Agent.GetTransform().Translation + StrafeDirection * StrafeSpeed, 3.0) #Strafe left
            else:
                MoveTo(Agent, Agent.GetTransform().Translation - StrafeDirection * StrafeSpeed, 3.0) #Strafe right
    
        RetreatFromPlayer(Player : agent) : void =
            PlayerDirection := GetDirectionToPlayer(Player)
            RetreatDirection := -PlayerDirection #Flee in the opposite direction
            MoveTo(Agent, Agent.GetTransform().Translation + RetreatDirection * StrafeSpeed, 5.0)
    
        StopMoving() : void =
            MoveTo(Agent, Agent.GetTransform().Translation, 0.1) # Effectively stops movement
    
        MoveTo(TargetAgent : agent, Destination : vector3, Speed : float) : void =
            if(MovableComp := TargetAgent.GetComponent(movable_component)):
                 MovableComp.MoveTo(Destination, Speed)
    
        GetDirectionToPlayer(Player : agent) : vector3 =
            PlayerLocation := Player.GetTransform().Translation
            AgentLocation := Agent.GetTransform().Translation
            return (PlayerLocation - AgentLocation).GetNormalized()
    
        # --------------------------------------------------
        # Attack Logic
        # --------------------------------------------------
        MaybeAttackPlayer(Player : agent) : void =
            if (CurrentTime := GetSimulationTime()):
                if (CurrentTime - LastAttackTime &gt;= 1.0 / FireRate):
                    if (Simulation.RandomFloat() &lt;= Accuracy): # Simulate accuracy
                        DealDamage(Player)
                        LastAttackTime = CurrentTime
                        Print("NPC Controller: Attacked player!")
                    else:
                        Print("NPC Controller: Missed attack!")
    
        DealDamage(Target : agent) : void =
            if (Damageable :? damageable_interface = Target):
                Damageable.Damage(DamageAmount)
    
        # --------------------------------------------------
        # Damage Handling
        # --------------------------------------------------
        HandleDamage(Victim : agent, Damage : float, Instigator : agent, HitLocation : vector3, HitNormal : vector3) : void =
            if (Victim = Agent):
                Health -= Floor(Damage)
                Print("NPC Controller: Health = {Health}")
                if (Health &lt;= 0):
                    HandleDeath()
    
        HandleDeath() : void =
            Print("NPC Controller: NPC Died!")
            if (AISpawnable := AIManager.GetAISpawnable()):
                AISpawnable.Despawn(); #Despawn the NPC
            else:
                Print("NPC Controller: Failed to get AISpawnable for despawn.")
    
        # --------------------------------------------------
        # Utility Functions
        # --------------------------------------------------
        FindNearestPlayer() : ?agent =
            AllPlayers := GetPlayers()
            if (AllPlayers.IsEmpty()):
                return option{}
    
            var NearestPlayer : ?agent = option{}
            var MinDistance : float = AggroRange * 2.0 # Start with a large distance
    
            for (Player : AllPlayers):
                if(Player.IsEliminated()):
                    continue #Skip eliminated players
    
                DistanceToPlayer := Distance(Agent.GetTransform().Translation, Player.GetTransform().Translation)
                if (DistanceToPlayer &lt; MinDistance):
                    NearestPlayer := option{Player}
                    MinDistance = DistanceToPlayer
    
            return NearestPlayer
    

    Instructions to Use in Fortnite Creative:

    1. Open Fortnite Creative: Launch Fortnite and go to the Creative hub.
    2. Create a New Island or Edit an Existing One: Start a new island or load one you want to modify.
    3. Add an AI Spawner Device:
      • Go to the Creative inventory.
      • Find the "AI Spawner" device and equip it to your hotbar.
      • Place the AI Spawner device in your island where you want the NPC to spawn. Configure the AI Spawner with the type of NPC you want.
    4. Add a Verse Device:
      • Go to the Creative inventory.
      • Find the "Verse Script" device and equip it to your hotbar.
      • Place the Verse Script device in your island.
    5. Paste the Verse Code:
      • Interact with the Verse Script device to open the Verse editor.
      • Delete the default code in the editor.
      • Copy and paste the entire Verse script provided above into the editor.
      • Click "Compile" to compile the script. If there are errors, carefully check the code you pasted against the original.
    6. Configure the Verse Device:
      • Select the Verse Script device in your island.
      • In the Details panel, find the section for your npc_controller script.
      • AIManager: Drag and drop your AI Spawner device into this slot. This connects the script to the NPC.
      • Adjust the other editable properties (AggroRange, RetreatRange, StrafeSpeed, MaxHealth, DamageAmount, Accuracy, FireRate) to fine-tune the NPC's behavior and difficulty.
    7. Test the NPC:
      • Start the game on your Creative island.
      • Approach the NPC. It should become "aggroed" (start attacking) when you get within the AggroRange.
      • Observe its behavior: strafing, attacking, and retreating.
      • Adjust the properties in the Verse device until you achieve the desired challenge and fun factor.

    Tips for Making the NPC More Fun:

    • Vary the Strafe Speed and Retreat Speed: Experiment with different speeds to make the NPC's movements less predictable.
    • Adjust Accuracy and Fire Rate: A lower accuracy with a higher fire rate can make the fight feel more chaotic and exciting.
    • Add Visual Effects: Use visual effects (from the Creative inventory) when the NPC attacks or takes damage to make the fight more engaging.
    • Consider Sound Effects: Add sound effects for attacks, movement, and death to enhance the experience.
    • Environmental Interaction: If you want to get really advanced, you could add code that makes the NPC take cover behind objects or use the environment to its advantage. This would require more complex logic.
    • Multiple NPCs: Use multiple AI Spawners and Verse devices to create groups of challenging NPCs. Adjust their stats slightly differently to provide variety.

    This script provides a solid foundation for creating a fun and challenging NPC in Fortnite Creative. Remember to experiment with the parameters to achieve the desired difficulty and play style!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.