Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

UE5 AI Hearing C++: Unreal Engine Perception Example 🎮 # UE5 AI Hearing C++: Unreal Engine Perception Example 🎮 #

blurry low resolution placeholder image UE5 AI Hearing C++
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. C++ C++ Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

UE5 AI Hearing C++: Unreal Engine Perception Example 🎮 #

Published: 2 years ago
5 minute read
Gunning Fog Index: 5.7
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

👂🏽 Unreal Engine AI Hearing Perception #

In this post, we see some example UE5 AI hearing C++ code. This can be used to have AI non-player characters (NPCs), in your game, react to audio stimuli. I used this code in an Unreal Engine game I created better to understand AI in Unreal. In the game, the player is a special agent on a hostile site, searching for some sensitive documents. The player wants to avoid getting caught by hostile AI NPCs on-site, and uses a drone to check when it is safe to move.

To make the game a little more difficult, I wanted the drone to emit a sound whenever it climbs, which the AI characters would be able to perceive and react to. That is where this code came in.

blurry low resolution placeholder image The player character is seen, confronted by a non-player character outside a brick building, inside a high-walled compound.
UE5 AI Hearing C++: Player character gets caught by NPC

Learning in Public #

I am learning Unreal Engine 5, and have found, generally, there is much more content on how to add features using blueprints, than using C++. Luckily, I found a fantastic and up-to-date UE5 C++ AI tutorial (link below), which covered the basics and sight perception. I used this sight perception code to have the hostile NPCs react to seeing the player, and extended it, adding audio perception, to produce the C++ code example below.

I hope you will find this useful. Also, please let me know if you value this style of learning in public content, especially if there are other topics you would like to see some content on.

🌟 Unreal Engine 5 Learning Resources #

I mentioned, Unreal Engine 5 C++ tutorials are harder to come across. There is some UE4 C++ content, though this often needs a lot of work to update it for use in UE5. On AI, I did find some fantastic resources though:

  • UE5 C++ AI Series by Mr Cxx : YouTube series of 25 videos, which start from the basics, using blackboards and behaviour trees, to patrol routes and more.
  • Learn all About AI in Unreal Engine 5 by Ryan Laley : Ryan focuses on Unreal Engine Editor blueprints, rather than C++, though the quality of the tutorials is right up there. If you prefer to set things up in blueprints, before trying C++, start here!

The official Unreal docs are also helpful for tweaking configurations.

I also found another series of tutorials on Unreal generally. I got inspiration for the drone from this series. Unfortunately, these Reids Channel tutorials  are a little older, and were created for Unreal Engine 4. That said, they are still worth a look, because the instruction is of such high quality.

🖥️ UE5 AI Hearing C++ Example Code #

My starting point for this code was the MrCxx UE5 C++ tutorial linked above. I added the hearing perception to the NPC_AIController CPP class, first adding a hearing perception field to the class in Source/Game/NPC_AIController.h:

Source/Game/NPC_AIController.h
cpp
    
1 #pragma once
2
3 #include "AIController.h"
4 #include "CoreMinimal.h"
5
6 #include "NPC_AIController.generated.h"
7
8 UCLASS()
9 class AIGAME_API ANPC_AIController : public AAIController {
10 GENERATED_BODY()
11
12 public:
13 explicit ANPC_AIController(FObjectInitializer const &ObjectInitializer);
14
15 protected:
16 void OnPossess(APawn *InPawn) override;
17
18 private:
19 class UAISenseConfig_Sight *SightConfig;
20 class UAISenseConfig_Hearing *HearingConfig;
21
22 void SetupPerceptionSystem();
23
24 UFUNCTION()
25 void OnTargetDetected(AActor *Actor, FAIStimulus const Stimulus);
26 };

Then, I updated the SetupPerceptionSystem method definition in the C++ counterpart, adding hearing perception:

Source/Game/NPC_AIController.cpp
cpp
    
31 // ...TRUNCATED
32
33 void ANPC_AIController::SetupPerceptionSystem() {
34 SightConfig =
35 CreateDefaultSubobject<UAISenseConfig_Sight>(TEXT("Sight Config"));
36 HearingConfig =
37 CreateDefaultSubobject<UAISenseConfig_Hearing>(TEXT("Hearing Config"));
38
39 if (SightConfig != nullptr || HearingConfig != nullptr) {
40 SetPerceptionComponent(*CreateDefaultSubobject<UAIPerceptionComponent>(
41 TEXT("Perception Component")));
42 }
43
44 if (SightConfig != nullptr) {
45 SightConfig->SightRadius = 500.F;
46 SightConfig->LoseSightRadius = SightConfig->SightRadius + 25.F;
47 SightConfig->PeripheralVisionAngleDegrees = 90.F;
48 SightConfig->SetMaxAge(
49 5.F); // seconds - perceived stimulus forgotten after this time
50 SightConfig->AutoSuccessRangeFromLastSeenLocation = 520.F;
51 SightConfig->DetectionByAffiliation.bDetectEnemies = true;
52 SightConfig->DetectionByAffiliation.bDetectFriendlies = true;
53 SightConfig->DetectionByAffiliation.bDetectNeutrals = true;
54
55 GetPerceptionComponent()->SetDominantSense(
56 *SightConfig->GetSenseImplementation());
57 GetPerceptionComponent()->ConfigureSense(*SightConfig);
58 }
59
60 if (HearingConfig != nullptr) {
61 HearingConfig->HearingRange = 10000.F;
62 HearingConfig->SetMaxAge(5.F);
63 HearingConfig->DetectionByAffiliation.bDetectEnemies = true;
64 HearingConfig->DetectionByAffiliation.bDetectFriendlies = true;
65 HearingConfig->DetectionByAffiliation.bDetectNeutrals = true;
66
67 GetPerceptionComponent()->ConfigureSense(*HearingConfig);
68 }
69
70 if (SightConfig != nullptr || HearingConfig != nullptr) {
71 GetPerceptionComponent()->OnTargetPerceptionUpdated.AddDynamic(
72 this, &ANPC_AIController::OnTargetDetected);
73 }
74 }

Finally, in this file, I updated the OnTargetDetected method, to register the sound stimulus as detected:

Source/Game/NPC_AIController.cpp
cpp
    
75 // ...TRUNCATED
76
77 void ANPC_AIController::OnTargetDetected(AActor *Actor,
78 FAIStimulus const Stimulus) {
79 if (auto *const player_character = Cast<AAIGameCharacter>(Actor)) {
80 GetBlackboardComponent()->SetValueAsBool("CanSeePlayer",
81 Stimulus.WasSuccessfullySensed());
82 } else
83 // check if the actor is the player drone
84 if (Actor->GetActorNameOrLabel() == "BP_Drone") {
85 {
86 GetBlackboardComponent()->SetValueAsBool(
87 "CanSeePlayer", Stimulus.WasSuccessfullySensed());
88 }
89 }
90 }

The hearing configuration is not too different to sight, just with fewer parameters. You can see the full hearing config in the UAISenseConfig_Hearing  docs.

🙉 Updating the AI Character to Receive Audio Stimuli #

One final step, similar to sight perception, is to register the character to receive audio stimuli. For this, I updated the SetupStimulusSource method in Source/Game/AIGameCharacter.cpp:

Source/Game/AIGameCharacter.cpp
cpp
    
1 // ...TRUNCATED
2
3 void AAIGameCharacter::SetupStimulusSource() {
4 StimulusSource = CreateDefaultSubobject<UAIPerceptionStimuliSourceComponent>(
5 TEXT("Stimulus"));
6 if (StimulusSource) {
7 StimulusSource->RegisterForSense(TSubclassOf<UAISense_Sight>());
8 StimulusSource->RegisterForSense(TSubclassOf<UAISense_Hearing>());
9 StimulusSource->RegisterWithPerceptionSystem();
10 }
11 }

🗳 Poll #

Which is your preferred UE5 C++ learning resource?
Voting reveals latest results.

🙌🏽 UE5 AI Hearing C++: Wrapping Up #

In this UE5 AI Hearing C++ post, we saw a code example for adding audio perception to your Unreal NPC. More specifically, we saw:

  • some links to tutorials for learning Unreal Engine 5 AI using blueprints and C++;
  • example C++ code for adding AI hearing perception; and
  • C++ code for registering a character to receive audio stimuli.

Do let me know if you found this content useful and would like to see more similar content. Also reach out if there is anything I could improve to provide a better experience for you.

🙏🏽 UE5 AI Hearing C++: Feedback #

If you have found this post useful, see links below for further related content on this site. Let me know if there are any ways I can improve on it. I hope you will use the code or starter in your own projects. Be sure to share your work on X, giving me a mention, so I can see what you did. Finally, be sure to let me know ideas for other short videos you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please consider supporting me through Buy me a Coffee.

blurry low resolution placeholder image ask Rodney X (formerly Twitter) avatar

Rodney

@askRodney

Just dropped a new post on what I have learned about setting up an AI non-player character in Unreal Engine 5 using C++, as well as some fantastic learning resources for UE5 AI in general.

Hope you find it useful!

https://t.co/vvOy5tyJyC #askRodney #gamedev #learncpp

— Rodney (@askRodney) February 14, 2024

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on X (previously Twitter) and also, join the #rodney  Element Matrix room. Also, see further ways to get in touch with Rodney Lab. I post regularly on Game Dev as well as Rust and C++ (among other topics). Also, subscribe to the newsletter to keep up-to-date with our latest projects.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
C++GAMING

Reposts:

Reposts

  • Gaming Feed profile avatar

Likes:

Likes

  • Andrew "Ace" Arsenault profile avatar
Reposts & likes provided by Mastodon & X via Webmentions.

Related Posts

blurry low resolution placeholder image Using Jolt with flecs & Dear ImGui: Game Physics Introspection 🔎

Using Jolt with flecs & Dear ImGui: Game Physics Introspection 🔎

c++
gaming
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.