Hey there!
Here is what I’d do to receive the results that you want:
First of all, I like to use multiple Behavior Trees for differing AI States (for e.g - Roaming/Attacking/etc.). So, I’d go ahead and create an Enumerator containing these AI States.
Then create a Blueprint Interface called BPI_ChangeAIState, which will contain just one function. Add the enumerator we’ve created to the INPUT of the function:
To continue, create an AI Controller and assign it to the AI character:
Inside the AI Controller, go to Class Settings and assign the Blueprint Interface:
Then go ahead and create your Behavior Trees & Blackboard. Be sure that the Blackboard is selected correctly in the Behavior Trees. In this case, I’ve created 2 behavior trees - one for Roaming and one for Attacking:
In the AI Controller, create a variable - “CurrentAIState” and set its variable type to be the enumerator we’ve created:
Under the functions tab, locate Interfaces and implement the “Change AI State” function by right clicking. Then, you can do something like this to run multiple trees according to the AI’s state:
Next, hop into the Blackboard and create 2 variables - “PlayerTarget” Object & “RandomLocation” Vector:
Set the “PlayerTarget” object variable base class to “Actor”:
Now that we’ve got that part done, we can now add an AIPerception Component to the character itself:
Next, setup the component like this:
And then right-click the AIPerception component and override “On Perception Updated”. Here, you can check what targets the AI sees, and accordingly, set blackboard values (in this case, we set “PlayerTarget”):
Quickly whip out some basic logic in the Roaming behavior tree:
The BTT_ChangeAIState task (create a variable “NewAIState” which is instance editable with the type of the enumerator we made at the first step):
The BTT_GetRandomPoint task (promote the radius to a variable & also create a blackboard key selector variable which is instance editable):
Next up, the Attacking behavior tree:
This should work properly! You can tweak out the AIPerception settings to your liking. Also in the “OnPerceptionUpdated” event, you can check if the perceived actor has a specific tag (such as “Player”) before setting the blackboard value for more accurate results.
Also, you can use a timed event to clear the “PlayerTarget” blackboard value when the AI loses sight, so it feels a bit more smarter
Hope this helps!